/* global React, ReactDOM, window */
const { useState: useStateA, useMemo: useMemoA } = React;
const { Hero, Thesis, TAMTreemap, ScenarioBuilder, Trajectory, Compete, Milestones, Team, VerticalDrawer, DataRoom, ENGINES, PRESETS, calc, fmt } = window;

function App() {
  const [tab, setTab] = useStateA('thesis');
  const [drawerVertical, setDrawerVertical] = useStateA(null);
  const [engines, setEngines] = useStateA(() => {
    const clone = {};
    Object.entries(ENGINES).forEach(([k, v]) => { clone[k] = { ...v }; });
    return clone;
  });
  const [pe, setPe] = useStateA(20);
  const [shares, setShares] = useStateA(39);

  const applyPreset = (key) => {
    const p = PRESETS[key];
    const next = {};
    Object.entries(ENGINES).forEach(([k, v]) => {
      const enabled = p.enable.includes(k);
      const over = p.cfg[k] || {};
      next[k] = { ...v, ...over, enabled };
    });
    setEngines(next);
    setPe(p.pe);
    setShares(p.shares);
  };

  // scenario topline for hero
  const scenarioNumbers = useMemoA(() => {
    let profit = 0, count = 0;
    Object.values(engines).forEach((e) => {
      const r = calc(e);
      profit += r.profit;
      if (e.enabled) count++;
    });
    const price = (profit * pe) / (shares * 1e6);
    return { price, profit, count };
  }, [engines, pe, shares]);

  const tabs = [
    { k: 'thesis', n: 'Thesis' },
    { k: 'markets', n: 'Markets' },
    { k: 'scenario', n: 'Scenario Model' },
    { k: 'trajectory', n: 'Trajectory' },
    { k: 'compete', n: 'Competitive Position' },
    { k: 'milestones', n: 'Milestones' },
    { k: 'team', n: 'Team & Ownership' },
    { k: 'dataroom', n: 'Data Room' },
  ];

  return (
    <div className="app">
      {/* Topbar */}
      <div className="topbar">
        <div className="wrap topbar-inner">
          <div className="brand">
            <div className="brand-mark" />
            <div>
              <div className="brand-name" style={{ whiteSpace: 'nowrap' }}>ADURO CLEAN TECH</div>
              <div className="brand-sub" style={{ whiteSpace: 'nowrap' }}>NASDAQ : ADUR · Investor Hub</div>
            </div>
          </div>
          <div className="ticker-rail">
            <div className="ticker-item">
              <span className="ticker-label">ADUR</span>
              <span className="ticker-val">$11.58</span>
              <span className="ticker-val pos">+0.24</span>
            </div>
            <div className="ticker-item">
              <span className="ticker-label">Scenario</span>
              <span className="ticker-val accent">${scenarioNumbers.price.toFixed(0)}</span>
            </div>
            <div className="ticker-item">
              <span className="ticker-dot" />
              <span className="ticker-label">Live Model</span>
            </div>
          </div>
        </div>
        <div className="wrap">
          <div className="navtabs">
            {tabs.map((t, i) => (
              <button key={t.k} className={`navtab ${tab === t.k ? 'active' : ''}`} onClick={() => setTab(t.k)}>
                <span className="navtab-num">{String(i + 1).padStart(2, '0')}</span>
                {t.n}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="wrap">
        <Hero
          scenarioPrice={scenarioNumbers.price}
          scenarioProfit={scenarioNumbers.profit}
          scenarioActiveCount={scenarioNumbers.count}
        />

        {tab === 'thesis' && <Thesis />}

        {tab === 'markets' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Markets</div>
                <div className="section-title serif">Thirteen verticals, one platform</div>
              </div>
              <div className="section-kicker">
                Treemap sized by estimated annual market volume (bbl-to-ton normalized for visual parity). Hover any cell for the thesis specific to that vertical.
              </div>
            </div>
            <TAMTreemap onOpen={setDrawerVertical} />
          </section>
        )}

        {tab === 'scenario' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Scenario Model</div>
                <div className="section-title serif">Build the thesis yourself</div>
              </div>
              <div className="section-kicker">
                Every engine below is a licensable revenue stream. Toggle them, tune share-of-market and unit economics, and see the implied valuation resolve in real time. Three preset anchors — Beachhead, Standard, Blue Sky — are starting points, not predictions.
              </div>
            </div>
            <ScenarioBuilder
              engines={engines}
              setEngines={setEngines}
              shares={shares}
              setShares={setShares}
              pe={pe}
              setPe={setPe}
              onApplyPreset={applyPreset}
            />
          </section>
        )}

        {tab === 'trajectory' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Trajectory</div>
                <div className="section-title serif">From pilot to platform standard</div>
              </div>
              <div className="section-kicker">
                Four phases, with drivers, catalysts, historical precedents, and the primary risk for each. Scroll or use the rail to navigate.
              </div>
            </div>
            <Trajectory engines={engines} />
          </section>
        )}

        {tab === 'compete' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Competitive Position</div>
                <div className="section-title serif">Different chemistry, different outcome</div>
              </div>
              <div className="section-kicker">
                Side-by-side against pyrolysis, coking, gasification, and mechanical recycling across the dimensions that matter to economics and regulatory compliance.
              </div>
            </div>
            <Compete />
          </section>
        )}

        {tab === 'milestones' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Milestones</div>
                <div className="section-title serif">Ten catalysts, four complete</div>
              </div>
              <div className="section-kicker">
                Each milestone removes a specific risk. Price impact estimates are the incremental repricing expected upon that risk being removed — not cumulative targets.
              </div>
            </div>
            <Milestones />
          </section>
        )}

        {tab === 'team' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Team & Ownership</div>
                <div className="section-title serif">Aligned for the long path</div>
              </div>
              <div className="section-kicker">
                Co-founder CEO, co-founding inventor-scientist, and a board drawn from chemical industry leadership (SSAB, Perstorp, Algonquin Power) and capital markets (Salomon Brothers, SBC Warburg). Combined insider ownership of 34–36% aligns management with multi-year commercialization rather than quarter-to-quarter activity.
              </div>
            </div>
            <Team />
          </section>
        )}

        {tab === 'dataroom' && (
          <section className="section">
            <div className="section-head">
              <div>
                <div className="section-num">§ Data Room</div>
                <div className="section-title serif">Every number, every source</div>
              </div>
              <div className="section-kicker">
                Consolidated reference for analysts and due-diligence review. Cross-vertical tables of economics, regulatory drivers, competitive verdicts, partnerships, risks and milestones — each traceable to primary disclosure.
              </div>
            </div>
            <DataRoom />
          </section>
        )}

        <footer className="footer">
          <div className="footer-grid">
            <div>
              <h4>Aduro Clean Technologies</h4>
              <p style={{ maxWidth: 520, color: 'var(--fg-2)' }}>
                A new chemistry for the hydrocarbon economy. Licensing Hydrochemolytic Technology globally across plastics recycling, heavy oil upgrading, and renewable oils conversion.
              </p>
            </div>
            <div>
              <h4>Filings</h4>
              <a href="#">Latest 10-Q</a>
              <a href="#">Investor Presentation</a>
              <a href="#">Patent Portfolio</a>
              <a href="#">WTR Coverage</a>
            </div>
            <div>
              <h4>Disclosure</h4>
              <p style={{ color: 'var(--fg-3)', fontSize: 11 }}>
                This investor hub is an analytical tool. The scenario model is illustrative and does not constitute forward-looking guidance. Always refer to official SEC filings for financial disclosures.
              </p>
            </div>
          </div>
          <div className="footer-bottom">
            <div>© ADUR INVESTOR HUB · DESIGN PROTOTYPE</div>
            <div>NASDAQ : ADUR · FY2026</div>
          </div>
        </footer>
      </div>

      {drawerVertical && (
        <VerticalDrawer vertical={drawerVertical} onClose={() => setDrawerVertical(null)} />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
