// Section 3 — "One platform, every asset" — tabbed module
const { IActivity, IArrowRight, IBank, IBuildings, IHome } = window;

function createLandingSparkRandom(seed) {
  let value = seed >>> 0;
  return () => {
    value = (value * 1103515245 + 12345) >>> 0;
    return value / 4294967296;
  };
}

function PlatformTabs() {
  const { t } = useLandingI18n();
  const tabs = [
    { id: 'inv', label: 'Investments' },
    { id: 'bank', label: 'Banking' },
    { id: 'rent', label: 'Rentals' },
    { id: 'crypto', label: 'Crypto' },
    { id: 're', label: 'Real estate' },
  ];
  const [active, setActive] = React.useState('inv');

  const content = {
    inv: {
      title: 'Stocks, ETFs, and funds — with an AI that ranks them.',
      body: 'Every holding scored by a seven-model ensemble. The ranker surfaces conviction, not noise — tabular, reproducible, and shown with its working.',
      bullets: ['ML stock ranker with confidence scoring', 'Volatility forecasting (Darts)', 'Sector rotation & regime detection', 'Monte Carlo outcome modeling'],
      viz: <InvestmentsViz/>,
    },
    bank: {
      title: 'Every account, reconciled automatically.',
      body: 'Open-banking connections across EU and US. Categorized, deduplicated, and reconciled against your investments and rental ledgers — one ledger, one truth.',
      bullets: ['PSD2 open banking (EU) and Plaid (US)', 'Auto-categorization with ML rules', 'Cashflow forecasting to 90 days', 'Custom budgets with envelope carry-over'],
      viz: <BankingViz/>,
    },
    rent: {
      title: 'Collect rent, meter utilities, close the books.',
      body: 'Track tenants, payments, and utility telemetry across every unit. Bank statement lines auto-match to invoices; late rent shows before you notice.',
      bullets: ['Tenant roster and lease management', 'Utility telemetry (water, gas, power)', 'Bank-to-invoice reconciliation', 'Per-unit P&L and tax-ready exports'],
      viz: <RentalsViz/>,
    },
    crypto: {
      title: 'Wallets and exchanges, in one ledger.',
      body: 'Read-only keys connect to major exchanges and wallets. Cost basis is computed per-lot; P&L flows into your overall portfolio with the same rigor as equities.',
      bullets: ['Binance, Kraken, Coinbase, wallet addresses', 'FIFO / HIFO / specific-lot cost basis', 'Staking rewards tracked as income', 'Tax reports: Portugal, Germany, UK, US'],
      viz: <CryptoViz/>,
    },
    re: {
      title: 'Properties as first-class assets.',
      body: 'Every property carries its own valuation curve, mortgage ledger, maintenance log, and yield calculation. Know your true ROI, not just the Zillow number.',
      bullets: ['Mortgage amortization + interest tracking', 'Maintenance and capex ledger', 'Gross and net yield per property', 'Valuation updates via market comps'],
      viz: <RealEstateViz/>,
    },
  };

  const c = content[active];

  return (
    <>
      <div className="tabs" role="tablist">
        {tabs.map((tab) => (
          <button key={tab.id}
            role="tab" aria-selected={active === tab.id}
            className={'tab ' + (active === tab.id ? 'is-active' : '')}
            onClick={() => setActive(tab.id)}>
            <span className="tab__dot"/> {t(tab.label)}
          </button>
        ))}
      </div>

      <div className="tab-panel" key={active} role="tabpanel">
        <div className="tab-panel__copy">
          <div className="eyebrow" style={{marginBottom: 10}}>01 · {t(tabs.find(tab => tab.id === active).label)}</div>
          <h3 className="display-md tab-panel__title">{t(c.title)}</h3>
          <p className="tab-panel__body">{t(c.body)}</p>
          <ul className="tab-panel__list">
            {c.bullets.map((b, i) => (
              <li key={i}>
                <span className="tab-panel__bullet">{String(i+1).padStart(2,'0')}</span>
                <span>{t(b)}</span>
              </li>
            ))}
          </ul>
          <a href="#" className="btn btn--ghost" style={{alignSelf:'flex-start', paddingLeft: 0}}>
            See how it works <IArrowRight size={16}/>
          </a>
        </div>
        <div className="tab-panel__viz">{c.viz}</div>
      </div>
    </>
  );
}

function InvestmentsViz() {
  const rows = [
    { sym: 'NVDA', name: 'NVIDIA Corp', score: 0.94, tone: 'gain' },
    { sym: 'MSFT', name: 'Microsoft', score: 0.89, tone: 'gain' },
    { sym: 'ASML', name: 'ASML Holding', score: 0.86, tone: 'gain' },
    { sym: 'BRK.B', name: 'Berkshire Hath.', score: 0.81, tone: 'gain' },
    { sym: 'AAPL', name: 'Apple Inc', score: 0.74, tone: 'neutral' },
    { sym: 'TSLA', name: 'Tesla', score: 0.41, tone: 'loss' },
  ];
  return (
    <div className="rank">
      <div className="rank__hd">
        <span>#</span><span>Holding</span><span>Conviction</span><span style={{textAlign:'right'}}>Score</span>
      </div>
      {rows.map((r, i) => (
        <div className="rank__row" key={r.sym} style={{animationDelay: `${i * 70}ms`}}>
          <div className="rank__rank">{String(i+1).padStart(2,'0')}</div>
          <div>
            <div className="rank__sym">{r.sym}</div>
            <div className="rank__name">{r.name}</div>
          </div>
          <div className="rank__bar" style={{width: 90}}>
            <div className="rank__bar-fill" style={{width: `${r.score * 100}%`, animationDelay: `${i * 70 + 200}ms`}}/>
          </div>
          <div className="rank__score num">{r.score.toFixed(2)}</div>
        </div>
      ))}
    </div>
  );
}

function BankingViz() {
  const rows = [
    { icon: <IBank size={14}/>, label: 'Millennium BCP', sub: 'IBAN ···· 4821', amt: '+ €4,208.00', tag: 'SALARY', tone: 'gain' },
    { icon: <IHome size={14}/>, label: 'Câmara Municipal Sintra', sub: 'IMI quarterly', amt: '− €412.60', tag: 'TAX' },
    { icon: <IBuildings size={14}/>, label: 'EDP Comercial', sub: 'Rental unit 6A', amt: '− €68.24', tag: 'UTILITY' },
    { icon: <IActivity size={14}/>, label: 'Rent · Mercês 3B', sub: 'From L. Fernandes', amt: '+ €850.00', tag: 'RENT', tone: 'gain' },
    { icon: <IBank size={14}/>, label: 'Interactive Brokers', sub: 'Dividend NVDA', amt: '+ €12.04', tag: 'DIVIDEND', tone: 'gain' },
  ];
  return (
    <div className="bank-list">
      {rows.map((r, i) => (
        <div className="bank-row" key={i} style={{animationDelay: `${i * 60}ms`}}>
          <div className="bank-row__icon">{r.icon}</div>
          <div>
            <div className="bank-row__label">{r.label}</div>
            <div className="bank-row__sub">{r.sub}</div>
          </div>
          <div className={'bank-row__amt ' + (r.tone === 'gain' ? 'gain' : '')}>{r.amt}</div>
          <div className="bank-row__tag">{r.tag}</div>
        </div>
      ))}
    </div>
  );
}

function RentalsViz() {
  const { t } = useLandingI18n();
  const units = [
    { addr: 'Mercês 6A', city: 'Sintra', rent: '850', state: 'paid', meter: 72, util: '€54 water · €38 gas' },
    { addr: 'Mercês 6B', city: 'Sintra', rent: '780', state: 'paid', meter: 48, util: '€41 water · €28 gas' },
    { addr: 'Cascais 3A', city: 'Cascais', rent: '1,200', state: 'due', meter: 88, util: '€72 water · €44 gas' },
    { addr: 'Mercês 3B', city: 'Sintra', rent: '820', state: 'paid', meter: 55, util: '€46 water · €31 gas' },
  ];
  return (
    <div className="unit-grid">
      {units.map((u, i) => (
        <div className="unit" key={i} style={{animationDelay: `${i * 80}ms`}}>
          <div className="unit__head">
            <div>
              <div className="unit__addr">{u.addr}</div>
              <div className="unit__city">{t(u.city)}</div>
            </div>
            <span className={'unit__state ' + (u.state === 'paid' ? 'unit__state--paid' : 'unit__state--due')}>
              {u.state === 'paid' ? t('PAID') : t('DUE 2d')}
            </span>
          </div>
          <div className="unit__rent num">€{u.rent}<span style={{fontSize:10,color:'var(--fg-3)',fontWeight:500}}>/mo</span></div>
          <div className="unit__meter"><div className="unit__meter-fill" style={{width: `${u.meter}%`}}/></div>
          <div className="unit__meta"><span>{t('Util {{meter}}%', { meter: u.meter })}</span><span>{t(u.util)}</span></div>
        </div>
      ))}
    </div>
  );
}

function CryptoViz() {
  const coins = [
    { sym: 'BTC', price: '62,481', chg: '+2.88%', pos: true },
    { sym: 'ETH', price: '3,214.40', chg: '+1.04%', pos: true },
    { sym: 'SOL', price: '148.22', chg: '−0.94%', pos: false },
    { sym: 'AVAX', price: '36.10', chg: '+3.21%', pos: true },
  ];
  const spark = (seed, pos) => {
    const random = createLandingSparkRandom(seed * 131 + (pos ? 17 : 29));
    const pts = [];
    let v = 50;
    for (let i = 0; i < 24; i++) {
      v += (random() - (pos ? 0.4 : 0.55)) * 8;
      pts.push(v);
    }
    const min = Math.min(...pts), max = Math.max(...pts), r = max - min || 1;
    const d = pts.map((p, i) => `${i===0?'M':'L'}${i*5} ${32 - ((p-min)/r)*28}`).join(' ');
    return d;
  };
  return (
    <div className="crypto-grid">
      {coins.map((c, i) => (
        <div className="crypto" key={c.sym} style={{animationDelay: `${i*70}ms`}}>
          <div className="crypto__sym">{c.sym}/EUR</div>
          <div className="crypto__price">€{c.price}</div>
          <div className={'crypto__chg ' + (c.pos ? 'gain' : 'loss')}>{c.chg} <span className="muted">· 24h</span></div>
          <svg className="crypto__spark" viewBox="0 0 120 36" preserveAspectRatio="none">
            <path d={spark(i, c.pos)} fill="none" stroke={c.pos ? '#0B8F4C' : '#C8321A'} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      ))}
    </div>
  );
}

function RealEstateViz() {
  return (
    <div className="re-map">
      <div className="eyebrow">Portfolio · 4 properties</div>
      <div className="num" style={{fontSize: 28, fontWeight: 700, letterSpacing:'-0.02em'}}>€1,248,000</div>
      <div className="num" style={{fontSize:12, color:'var(--fg-2)', marginBottom: 8}}>+4.2% YoY · vs €1,197,600 LY</div>
      <div style={{borderTop:'1px solid var(--border-subtle)', paddingTop: 8}}>
        <div className="re-stat"><span className="re-stat__k">Mortgage outstanding</span><span className="re-stat__v">€482,100</span></div>
        <div className="re-stat"><span className="re-stat__k">Net equity</span><span className="re-stat__v">€765,900</span></div>
        <div className="re-stat"><span className="re-stat__k">Gross yield</span><span className="re-stat__v gain">6.8%</span></div>
        <div className="re-stat"><span className="re-stat__k">Net yield (TTM)</span><span className="re-stat__v gain">4.2%</span></div>
        <div className="re-stat"><span className="re-stat__k">Occupancy</span><span className="re-stat__v">100%</span></div>
      </div>
    </div>
  );
}

Object.assign(window, { PlatformTabs });
