/* ===================================================================
   APP - hub shell: tool tabs + desktop/mobile device toggle.

   URLs: the Benefit + EV calculators share the main page (switch via
   tabs); the partner Embed widget gets its own URL so it can be linked
   / iframed distinctly:
     /        -> calculator suite (Benefit + EV tabs)
     /embed   -> embeddable widget
   The calculators host rewrites every path to this index.html
   (see vercel.json), so navigation is client-side via the history API.
   =================================================================== */
const { useState: useStateApp, useEffect: useEffectApp } = React;

const ORIGIN = 'https://calculators.covase.co.uk';

// Public nav tabs. The embed widget is intentionally NOT listed — it's a
// partner-only artifact, reached directly at /embed (the iframe target we
// hand to a partner when they adopt the tool), not advertised to visitors.
const TABS = [
  { id: 'a', label: 'Benefit Calculator', sub: 'Home energy' },
  { id: 'b', label: 'EV salary sacrifice', sub: 'Cars · BIK' },
];

const EMBED_PATH = '/embed';
function toolFromPath(p) { return p === EMBED_PATH ? 'e' : 'a'; }
function pathForTool(id) { return id === 'e' ? EMBED_PATH : '/'; }
function metaForTool(id) {
  if (id === 'e') return {
    path: EMBED_PATH,
    title: 'Embeddable EV calculator widget · Perx by Covase',
    noindex: true,   // partner-only page — keep it out of search results
  };
  return {
    path: '/',
    title: 'Perx Calculators — Benefit · EV salary sacrifice · Perx by Covase',
    noindex: false,
  };
}

function App() {
  // Initial tab: '/embed' opens the widget; otherwise restore last-used
  // tab (Benefit or EV) from localStorage, defaulting to Benefit.
  const [tool, setTool] = useStateApp(() => {
    if (location.pathname === EMBED_PATH) return 'e';
    const saved = localStorage.getItem('pt.tool');
    return (saved === 'a' || saved === 'b') ? saved : 'a';
  });
  useEffectApp(() => { if (tool === 'a' || tool === 'b') localStorage.setItem('pt.tool', tool); }, [tool]);

  // "bare" iframe mode: /embed?bare=1 renders ONLY the widget (no nav/
  // chrome) — this is the actual iframe src a partner drops into their
  // site. Plain /embed shows the in-context showcase for evaluation.
  const bare = tool === 'e' && /[?&]bare=1\b/.test(location.search);

  // Reflect the active tool in the URL, <title>, canonical and robots.
  useEffectApp(() => {
    const m = metaForTool(tool);
    const want = m.path + (bare ? location.search : '');
    if (location.pathname !== m.path) history.pushState({ tool }, '', want);
    document.title = m.title;
    let link = document.querySelector('link[rel="canonical"]');
    if (!link) { link = document.createElement('link'); link.rel = 'canonical'; document.head.appendChild(link); }
    link.href = ORIGIN + (m.path === '/' ? '/' : m.path);
    // partner-only embed page should not be indexed
    let robots = document.querySelector('meta[name="robots"]');
    if (!robots) { robots = document.createElement('meta'); robots.name = 'robots'; document.head.appendChild(robots); }
    robots.content = m.noindex ? 'noindex, follow' : 'index, follow';
  }, [tool, bare]);

  // Back/forward buttons switch between the suite and the embed page.
  useEffectApp(() => {
    const onPop = () => setTool(toolFromPath(location.pathname));
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const render = () => {
    if (tool === 'a') return <ToolA />;
    if (tool === 'b') return <ToolB />;
    return <EmbedShowcase />;
  };

  // Bare iframe payload — just the widget, no app shell.
  if (bare) {
    return <div className="pt-embed-bare"><EmbedWidget /></div>;
  }

  return (
    <div className="pt-app">
      <nav className="pt-nav">
        <Wordmark sub="Calculator suite" />
        <div className="pt-tabs">
          {TABS.map(t => (
            <a key={t.id} href={pathForTool(t.id)}
               className={'pt-tab' + (tool === t.id ? ' on' : '')}
               onClick={(e) => { e.preventDefault(); setTool(t.id); }}>
              <span className="dot"></span>{t.label}
            </a>
          ))}
        </div>
      </nav>
      <div className="pt-stage">
        <div className="pt-canvas fade-in" key={tool}>{render()}</div>
      </div>
    </div>
  );
}

// Mount once the live EV ratebook (evs.json) has loaded, so the EV tool
// renders with real pricing rather than a flash of the fallback list.
const _root = ReactDOM.createRoot(document.getElementById('root'));
const _mount = () => _root.render(<App />);
(PX.evsReady && PX.evsReady.then ? PX.evsReady.then(_mount, _mount) : _mount());
