/* Email Triage — public marketing page for the sellable Email Triage feature.

   Ported from packages/web-portal/src/pages/features/EmailTriage.tsx (portal
   route /features/email-triage) as part of the portal-5-page redesign — public
   marketing pages don't belong behind/inside the authenticated web-portal
   bundle, they belong on the marketing site. Layout follows
   page-features-cave-recorder.jsx: section components composed into one Page
   function, using Header / Footer / StampBadge / Underline / Ico from
   shared.jsx + page-home.jsx. Static site, no build step — same as every
   other page here.

   CTAs point at the portal app (app.mammoth-dev.com) instead of an in-app
   <Link>, since this page is served from a separate static origin and can't
   use react-router. /inbox-rules bounces to /login if the visitor isn't
   signed in, same behavior as the original portal page.
*/

const ET = {
  brandName: () => (typeof window !== 'undefined' && window.MAMMOTH_BRAND_NAME) || 'Mammoth-dev',
  appUrl: (path) => `https://app.mammoth-dev.com${path}`,
};

function TriageHero() {
  return (
    <section className="m-section" style={{paddingTop:56, paddingBottom:40}}>
      <div className="m-container" style={{textAlign:'center', maxWidth:880}}>
        <StampBadge color="var(--russet)">New · Sellable feature</StampBadge>
        <h1 style={{marginTop:20, marginBottom:20, textWrap:'balance'}}>
          Smart email triage with <Underline>human-in-the-loop.</Underline>
        </h1>
        <p className="lead" style={{margin:'0 auto 32px', maxWidth:700}}>
          Auto-route inbound email with Claude Haiku. High-confidence decisions
          fire your webhook directly. Low-confidence ones push a tap-to-choose
          notification to your phone, so a human stays in control of the edge
          cases — and only the edge cases.
        </p>
        <div className="m-row" style={{justifyContent:'center', gap:12}}>
          <a href={ET.appUrl('/inbox-rules')} className="m-btn m-btn-russet m-btn-lg">
            Configure a rule {Ico.arrow(16,'currentColor')}
          </a>
          <a href="#how-it-works" className="m-btn m-btn-ghost m-btn-lg">
            See how it works
          </a>
        </div>
      </div>
    </section>
  );
}

function TriageFlowDiagram() {
  return (
    <div className="m-card" style={{marginTop:32, padding:20, overflowX:'auto'}}>
      <svg
        viewBox="0 0 880 220"
        style={{width:'100%', maxWidth:880, height:'auto', display:'block'}}
        role="img"
        aria-label="Email triage flow diagram"
      >
        <TriageFlowBox x={20} y={80} w={140} h={60} title="Inbound email" sub="Outlook / Gmail" fill="#e8f0ff" />
        <TriageFlowArrow from={[160, 110]} to={[200, 110]} />

        <TriageFlowBox x={200} y={80} w={140} h={60} title="Rule match" sub="from / subject / cat" fill="#fff7e0" />
        <TriageFlowArrow from={[340, 110]} to={[380, 110]} />

        <TriageFlowBox x={380} y={80} w={140} h={60} title="Haiku triage" sub="prompt + options" fill="#ede7ff" />
        <TriageFlowArrow from={[520, 110]} to={[560, 110]} />

        <polygon points="560,110 600,80 640,110 600,140" fill="#fef2f7" stroke="#c66" strokeWidth={1.5} />
        <text x={600} y={108} textAnchor="middle" fontSize={11} fontWeight={600} fill="#a33">conf ≥</text>
        <text x={600} y={122} textAnchor="middle" fontSize={11} fontWeight={600} fill="#a33">threshold?</text>

        <TriageFlowArrow from={[640, 95]} to={[700, 50]} />
        <text x={665} y={70} fontSize={11} fill="#0a0" fontWeight={600}>yes</text>
        <TriageFlowBox x={700} y={20} w={160} h={60} title="Auto-fire webhook" sub="chosen action_url" fill="#dfe9d0" />

        <TriageFlowArrow from={[640, 130]} to={[700, 170]} />
        <text x={665} y={160} fontSize={11} fill="#a40" fontWeight={600}>no</text>
        <TriageFlowBox x={700} y={140} w={160} h={60} title="Phone tap-to-choose" sub="grug-phone push" fill="#fde4d0" />
      </svg>
    </div>
  );
}

function TriageHowItWorks() {
  const steps = [
    { n:'1', title:'Inbound email arrives', body:'Outlook Graph subscription (or Gmail Pub/Sub) hits the router. Existing inbox rules match by from / subject / category / folder.' },
    { n:'2', title:'Haiku triages', body:'Your prompt + 2–8 action options are passed to Claude Haiku. It returns a chosen index, a confidence score, and a one-line reason.' },
    { n:'3', title:'High conf → auto-fire', body:"If confidence ≥ your threshold, the chosen option's webhook fires directly. Optional payload merges into the POST body." },
    { n:'4', title:'Low conf → human', body:'If under threshold, a tap-to-choose card lands on your phone via grug-phone. Whichever button you tap fires that option\'s webhook.' },
  ];
  return (
    <section id="how-it-works" className="m-section m-section-alt">
      <div className="m-container">
        <div style={{textAlign:'center', marginBottom:24}}>
          <StampBadge>How it works</StampBadge>
          <h2 style={{marginTop:16, marginBottom:8}}>Configure once per inbox rule.</h2>
          <p className="lead" style={{maxWidth:640, margin:'0 auto'}}>
            The pipeline runs on every matching inbound email — Outlook today, Gmail next.
          </p>
        </div>

        <TriageFlowDiagram />

        <div className="m-grid m-grid-2" style={{gap:20, marginTop:40}}>
          {steps.map((s, i) => (
            <div key={i} className="m-card" style={{display:'flex', gap:16, alignItems:'flex-start'}}>
              <div style={{width:28, height:28, borderRadius:14, background:'var(--russet)', color:'var(--cream)', fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, flexShrink:0}}>
                {s.n}
              </div>
              <div>
                <div style={{fontWeight:700, fontSize:16, marginBottom:6}}>{s.title}</div>
                <p style={{margin:0, fontSize:14, color:'var(--charcoal-soft)'}}>{s.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function TriagePricing() {
  const tiers = [
    { name:'Free', price:0, quota:'100 triages / mo', featured:false,
      includes:['Up to 2 inbox rules','Confidence threshold control','Phone tap-to-choose fallback','Preview tool'] },
    { name:'Pro', price:29, quota:'Unlimited triages', featured:true,
      includes:['Unlimited inbox rules','Per-rule prompt + options','Phone tap-to-choose fallback','Preview + audit log','Email support'] },
    { name:'Team', price:99, quota:'Unlimited + team escalation', featured:false,
      includes:['Everything in Pro','Escalate low-conf to a teammate','Per-user phone tokens','Shared rule library','Priority support'] },
  ];
  return (
    <section className="m-section">
      <div className="m-container">
        <div style={{textAlign:'center', marginBottom:48}}>
          <StampBadge>Pricing</StampBadge>
          <h2 style={{marginTop:16}}>Triage decisions counted per inbound email.</h2>
          <p className="lead" style={{maxWidth:640, margin:'8px auto 0'}}>
            Webhook calls and tap notifications are always free.
          </p>
        </div>
        <div className="m-grid m-grid-3" style={{gap:20, alignItems:'stretch'}}>
          {tiers.map((t, i) => (
            <div key={i} className={'m-price-card' + (t.featured ? ' featured' : '')}>
              {t.featured && <div className="m-badge-popular">Most popular</div>}
              <div className="m-price-tier-name">{t.name}</div>
              <div className="m-price-amount">
                <span className="big">${t.price}</span>
                <span className="cycle">/mo</span>
              </div>
              <div style={{fontSize:13, color:'var(--charcoal-soft)', fontWeight:600}}>{t.quota}</div>
              <div style={{height:1, background:'var(--mist)'}} />
              <ul className="m-checklist" style={{gap:10}}>
                {t.includes.map((it, j) => (
                  <li key={j} style={{fontSize:14}}>
                    <span className="m-check" style={{width:20, height:20}}>{Ico.check(11,'white')}</span>
                    <span>{it}</span>
                  </li>
                ))}
              </ul>
              <a
                href={t.name === 'Team' ? ET.appUrl('/inbox-rules') : ET.appUrl('/signup')}
                className={'m-btn ' + (t.featured ? 'm-btn-gold' : 'm-btn-russet')}
                style={{justifyContent:'center', marginTop:'auto'}}
              >
                {t.name === 'Free' ? 'Start free' : t.name === 'Team' ? 'Talk to sales' : 'Upgrade'} {Ico.arrow(16,'currentColor')}
              </a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function TriageCTAFooter() {
  return (
    <section className="m-section m-section-russet">
      <div className="m-container" style={{textAlign:'center', maxWidth:720}}>
        <StampBadge color="var(--gold)">Stop reading every email yourself</StampBadge>
        <h2 style={{marginTop:16, color:'var(--cream)'}}>Set a triage rule in under five minutes.</h2>
        <p style={{color:'rgba(255,253,249,0.85)', fontSize:18, marginBottom:28}}>
          Test it against a sample email with the built-in preview. Flip the toggle when you're happy.
        </p>
        <a href={ET.appUrl('/inbox-rules')} className="m-btn m-btn-gold m-btn-lg">
          Configure your first triage rule {Ico.arrow(16,'currentColor')}
        </a>
      </div>
    </section>
  );
}

function FeaturesEmailTriagePage() {
  return (
    <div className="m-root">
      <Header current="" />
      <TriageHero />
      <TriageHowItWorks />
      <TriagePricing />
      <TriageCTAFooter />
      <Footer />
    </div>
  );
}

// ─── Small shared SVG helpers (mirrors page-features-cave-recorder.jsx style
// of keeping the page fully self-contained) ─────────────────────────────────

function TriageFlowBox({ x, y, w, h, title, sub, fill }) {
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={6} fill={fill} stroke="#bbb" strokeWidth={1} />
      <text x={x + w / 2} y={y + 25} textAnchor="middle" fontSize={13} fontWeight={700} fill="#222">{title}</text>
      <text x={x + w / 2} y={y + 44} textAnchor="middle" fontSize={11} fill="#555">{sub}</text>
    </g>
  );
}

function TriageFlowArrow({ from, to }) {
  const [x1, y1] = from;
  const [x2, y2] = to;
  const angle = Math.atan2(y2 - y1, x2 - x1);
  const a = 6;
  const ax = x2 - a * Math.cos(angle - Math.PI / 6);
  const ay = y2 - a * Math.sin(angle - Math.PI / 6);
  const bx = x2 - a * Math.cos(angle + Math.PI / 6);
  const by = y2 - a * Math.sin(angle + Math.PI / 6);
  return (
    <g stroke="#888" strokeWidth={1.5} fill="none">
      <line x1={x1} y1={y1} x2={x2} y2={y2} />
      <line x1={x2} y1={y2} x2={ax} y2={ay} />
      <line x1={x2} y1={y2} x2={bx} y2={by} />
    </g>
  );
}

Object.assign(window, { FeaturesEmailTriagePage });
