/* ==========================================================
   NewsNator — Pages: Trends, Archive, About, Opt-out
   ========================================================== */

// ============= TRENDS LIST PAGE ==========================
function TrendsListPage() {
  return (
    <div className="page-enter" style={{padding:'56px 0 80px'}}>
      <div className="container">
        <div className="eyebrow mb-4">/ {t('nav_trends')}</div>
        <h1 className="title-xl" style={{marginBottom:14}}>
          {window.__lang === 'zh' ? '本周趋势' : 'Trends this week'}
        </h1>
        <p className="lede" style={{maxWidth:'58ch', marginBottom: 40}}>
          {window.__lang === 'zh'
            ? '本周识别出的主题，附本周热度分数和相关事件。'
            : 'Themes across this week\'s 47 events, scored by dominance and linked to source events.'}
        </p>

        <div style={{display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:20}}>
          {THIS_WEEK.trends.map(tr => {
            const name = window.__lang === 'zh' ? tr.nameZh : tr.name;
            const related = EVENTS.filter(e => tr.eventIds.includes(e.id));
            return (
              <a key={tr.slug} href={`/trends/${tr.slug}`} className="card card-hover" style={{padding:'28px', color:'var(--fg)', textDecoration:'none'}}>
                <div className="flex items-center gap-3 mb-4">
                  <div className="eyebrow">TREND</div>
                  <div className="grow"/>
                  <div className="num mono" style={{fontSize:16, fontWeight:600, color:'var(--accent)'}}>{tr.score}</div>
                </div>
                <h2 className="title-md" style={{marginBottom:14}}>{name}</h2>
                <div style={{height:6, background:'var(--bg-sunken)', borderRadius:3, marginBottom:18, overflow:'hidden'}}>
                  <div style={{height:'100%', width: tr.score + '%', background:'var(--accent)'}}/>
                </div>
                <div className="flex items-center gap-2">
                  {related.slice(0, 3).map(e => {
                    const m = makerBySlug(e.makerSlug);
                    return <span key={e.id} style={{marginLeft:-4}}><Avatar maker={m} size={26}/></span>;
                  })}
                  <span className="mono faint ml-2" style={{fontSize:11, marginLeft:8}}>
                    {tr.eventIds.length} related events →
                  </span>
                </div>
              </a>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ============= TREND DETAIL PAGE =========================
function TrendDetailPage({ slug }) {
  const trend = THIS_WEEK.trends.find(t => t.slug === slug);
  if (!trend) return (
    <div style={{padding:'120px 0', textAlign:'center'}}><div className="container"><h1 className="title-xl">Trend not found</h1><a href="/trends" className="btn mt-6">← Back</a></div></div>
  );
  const name = window.__lang === 'zh' ? trend.nameZh : trend.name;
  const related = EVENTS.filter(e => trend.eventIds.includes(e.id));

  // ai-generated description
  const desc = window.__lang === 'zh'
    ? `本周有 ${related.length} 条事件被归入"${name}"。makers 不再把"运多个 SaaS"当成炫耀指标 —— 反而开始展示自家产品之间的闭环、共享流量、共享 prompt 资产。这是从"产品组合"转向"产品生态"的临界点。`
    : `${related.length} events this week were grouped into "${name}". Makers are no longer treating "running many SaaS" as the brag — they're showing the loops between their own products: shared traffic, shared prompts, shared user identity. This is the moment the genre shifts from "portfolio" to "ecosystem".`;

  return (
    <div className="page-enter">
      <section style={{borderBottom:'1px solid var(--border)', background:'var(--bg-elev)', padding:'56px 0'}}>
        <div className="container">
          <div className="eyebrow mb-4">
            <a href="/trends" style={{color:'var(--fg-muted)'}}>{t('nav_trends')}</a> / {trend.slug}
          </div>
          <h1 className="title-xxl" style={{marginBottom:24, maxWidth:'18ch'}}>{name}</h1>
          <div className="flex items-center gap-4 mb-6">
            <div style={{padding:'6px 12px', borderRadius:'var(--r-sm)', background:'var(--accent-soft)', color:'var(--accent)', fontFamily:'var(--font-mono)', fontWeight:600, fontSize:13}}>
              {trend.score} {t('trend_score')}
            </div>
            <div className="mono faint" style={{fontSize:12}}>{related.length} events · week {THIS_WEEK.yearWeek.split('-W')[1]}</div>
          </div>
          <p className="lede" style={{maxWidth:'60ch'}}>{desc}</p>
        </div>
      </section>

      <div className="container" style={{padding:'56px 32px 80px'}}>
        <div className="section-head">
          <h2 className="title-lg">{t('trend_related')}</h2>
          <span className="count">{related.length}</span>
        </div>
        <div style={{display:'grid', gap:20}}>
          {related.map(ev => <EventCard key={ev.id} event={ev}/>)}
        </div>
      </div>
    </div>
  );
}

// ============= ARCHIVE PAGES =============================
function ArchiveListPage() {
  return (
    <div className="page-enter" style={{padding:'56px 0 80px'}}>
      <div className="container">
        <div className="eyebrow mb-4">/ {t('nav_archive')}</div>
        <h1 className="title-xl" style={{marginBottom:14}}>{t('archive_heading')}</h1>
        <p className="lede" style={{maxWidth:'58ch', marginBottom: 40}}>{t('archive_subhead', { n: ARCHIVE.length })}</p>

        <div className="card" style={{padding:'4px 24px'}}>
          {ARCHIVE.map((issue, i) => {
            const isCurrent = i === 0;
            return (
              <a key={issue.yearWeek} href={`/archive/${issue.yearWeek}`} className="row-line"
                 style={{gridTemplateColumns:'140px 1fr 120px 100px', textDecoration:'none', color:'var(--fg)'}}>
                <span className="flex items-center gap-3">
                  <span className="mono" style={{fontSize:13, fontWeight:500}}>{issue.yearWeek}</span>
                  {isCurrent && <span className="chip chip-accent">current</span>}
                </span>
                <span style={{fontWeight:500, fontSize:15}}>{issue.headline}</span>
                <span className="mono faint" style={{fontSize:11, textAlign:'right'}}>{issue.date}</span>
                <span className="mono faint" style={{fontSize:11, textAlign:'right'}}>{issue.events} events</span>
              </a>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ArchiveWeekPage({ yearWeek }) {
  const issue = ARCHIVE.find(a => a.yearWeek === yearWeek);
  if (!issue) {
    return (
      <div style={{padding:'120px 0', textAlign:'center'}}>
        <div className="container">
          <h1 className="title-xl">Archive not found</h1>
          <a href="/archive" className="btn mt-6">← Back</a>
        </div>
      </div>
    );
  }

  return (
    <div className="page-enter">
      <section style={{borderBottom:'1px solid var(--border)', background:'var(--bg-elev)', padding:'56px 0'}}>
        <div className="container">
          <div className="eyebrow mb-4">
            <a href="/archive" style={{color:'var(--fg-muted)'}}>{t('nav_archive')}</a> / {yearWeek}
          </div>
          <h1 className="title-xxl" style={{maxWidth:'18ch', marginBottom:24}}>{issue.headline}</h1>
          <div className="mono faint" style={{fontSize:13}}>
            {issue.date} · {issue.events} tracked events
          </div>
        </div>
      </section>

      <div className="container" style={{padding:'56px 32px 80px'}}>
        <div className="card" style={{padding:'56px', textAlign:'center'}}>
          <div className="ai-strip" style={{justifyContent:'center', marginBottom:24}}>
            <span className="ai-strip-dot"/>
            <span>Archived issue · static snapshot</span>
          </div>
          <h2 className="title-lg" style={{marginBottom:16}}>This week's full digest is in the archive.</h2>
          <p className="lede" style={{maxWidth:'46ch', margin:'0 auto 32px'}}>
            All events, trends and tool mentions from week {yearWeek} are preserved as a permanent record — usable as a citation in newsletters and posts.
          </p>
          <div className="flex items-center gap-3" style={{justifyContent:'center'}}>
            <a className="btn btn-primary" href="/">Read this week instead →</a>
            <a className="btn" href="/archive">← All archives</a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============= ABOUT PAGE ================================
function AboutPage() {
  return (
    <div className="page-enter" style={{padding:'56px 0 80px'}}>
      <div className="container-narrow">
        <div className="eyebrow mb-4">/ {t('nav_about')}</div>
        <h1 className="title-xxl" style={{marginBottom:32, maxWidth:'18ch'}}>
          {window.__lang === 'zh' ? '关于 opc.how' : 'A weekly record of indie SaaS.'}
        </h1>
        <p className="lede" style={{marginBottom: 24}}>
          {window.__lang === 'zh'
            ? 'opc.how 是一份每周摘要 —— 把 100 位独立创业者的 RSS、X、GitHub、Product Hunt 动态自动聚合、按主题归档。'
            : 'opc.how is a weekly digest. We pull RSS, X, GitHub and Product Hunt activity from 100 indie builders and group it by theme.'}
        </p>

        <div className="hr mt-8 mb-8"/>

        {/* THE LOGO STORY */}
        <h2 className="title-lg mb-4">{window.__lang === 'zh' ? '这是 OPC 心电图' : 'Meet the OPC pulse'}</h2>

        <div style={{padding:'56px 32px', background:'var(--bg-elev)', border:'1px solid var(--border)', borderRadius:'var(--r-lg)', marginBottom:24, display:'flex', justifyContent:'center'}}>
          <svg width="540" height="160" viewBox="0 0 56 16" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
            <path d="M24.4443 10.2217L27.792 4.00586L29.7207 8.08691H46.4746L49.5742 4.20703L52.207 6.57031L54.708 2.70703L55.2539 3.05957L55.7998 3.41309L52.4727 8.55469L49.7295 6.09375L47.2949 9.14258L47.1006 9.38672H28.8975L27.7158 6.8877L24.0635 13.6719L21.3154 3.89453L18.5273 10.3945L16.3408 7.32617L13.6602 10.6982L9.69434 7.15918L4.80469 12.5127L2.45312 9.52832L0.507812 10.3535L0 9.15625L2.86035 7.94434L4.87793 10.5039L9.16797 5.80859L9.60059 5.33398L13.499 8.81152L16.3975 5.16699L18.2441 7.75684L21.5723 0L24.4443 10.2217Z" fill="#FF6A00"/>
          </svg>
        </div>

        <p className="lede" style={{marginBottom:20}}>
          {window.__lang === 'zh'
            ? 'logo 上那根橙色的线，我们叫它 OPC 心电图 —— 是每一位 OPC（One Person Company）的真实轨迹。一份报表上的增长曲线，一段心跳，两个读法都对。'
            : 'The orange line on the logo — we call it the OPC pulse — is the real trajectory of every OPC (One Person Company). A growth chart, a heartbeat: both readings are right.'}
        </p>

        <p style={{margin:'0 0 16px', fontSize:15, lineHeight:1.65, color:'var(--fg-soft)'}}>
          {window.__lang === 'zh'
            ? '它有高高低低的起伏 —— 有 launch 当晚的高峰，也有 churn 爬升那几周的低谷。它也有暂时停下来、几乎平稳的那一段 —— 比如有的产品在 $10K MRR 上原地盘整十二个月，没坏掉，但也没在长。'
            : 'It has peaks — launch nights, milestone posts, the day MRR doubles. It has valleys — churn weeks, a kill at $480, the inbox going cold. And it has those flat stretches in the middle — a product idling at $10K MRR for twelve months straight, neither dying nor growing.'}
        </p>
        <p style={{margin:'0 0 28px', fontSize:15, lineHeight:1.65, color:'var(--fg-soft)'}}>
          {window.__lang === 'zh'
            ? '但真正的 OPC 不会放弃。他们会重新出发 —— fork 一个新方向，杀掉一个不挣钱的产品，写下一封 newsletter。所以心电图最终一路爬升、收尾时朝上。'
            : 'But real OPCs don\'t quit. They restart — they fork a new direction, kill the dead branch, write the next newsletter. So the pulse, in the end, keeps climbing.'}
        </p>

        {/* Annotated stages */}
        <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:12, marginBottom:8}}>
          {[
            { svg: 'peak',    label: window.__lang === 'zh' ? '高峰' : 'Peak',     note: window.__lang === 'zh' ? '一次发布、一笔 $8M 退出。' : 'A launch night. An $8M exit.' },
            { svg: 'valley',  label: window.__lang === 'zh' ? '低谷' : 'Valley',   note: window.__lang === 'zh' ? 'Churn 爬升的那几周。' : 'Churn weeks. The $480 kill.' },
            { svg: 'plateau', label: window.__lang === 'zh' ? '停顿' : 'Pause',    note: window.__lang === 'zh' ? '没死，但也没在涨。' : 'Not dying. Not growing.' },
            { svg: 'restart', label: window.__lang === 'zh' ? '重新出发' : 'Restart', note: window.__lang === 'zh' ? '下一封 newsletter。' : 'Next newsletter. Next fork.' },
          ].map((stage, i) => (
            <div key={i} style={{padding:'16px 14px', border:'1px solid var(--border)', borderRadius:'var(--r-md)', background:'var(--bg)'}}>
              <LogoStageMark variant={stage.svg}/>
              <div className="mono mt-2" style={{fontSize:11, fontWeight:600, color:'var(--fg)', letterSpacing:'0.02em'}}>{stage.label}</div>
              <div className="mono faint" style={{fontSize:10, marginTop:3, lineHeight:1.5}}>{stage.note}</div>
            </div>
          ))}
        </div>

        <div className="hr mt-8 mb-8"/>

        <h2 className="title-lg mb-4">{window.__lang === 'zh' ? '方法' : 'How it works'}</h2>
        <div style={{display:'grid', gap:24}}>
          {[
            { n: '01', t: window.__lang === 'zh' ? '抓取' : 'Fetch',  d: window.__lang === 'zh' ? '每天 06:00 UTC 自动抓取 100 个创业者的 RSS、X、GitHub releases、Product Hunt 发布。' : 'Every day at 06:00 UTC we pull RSS, X, GitHub releases and Product Hunt launches from 100 tracked builders.' },
            { n: '02', t: window.__lang === 'zh' ? '总结' : 'Summarize',  d: window.__lang === 'zh' ? '每条原文压成 80–150 词的英文摘要，抽取提到的工具和具体数字。数字必须来自原文，不允许推测。' : 'Each item is compressed to an 80–150 word English summary, with mentioned tools and exact numbers extracted. Numbers must come from the source — never inferred.' },
            { n: '03', t: window.__lang === 'zh' ? '翻译' : 'Translate', d: window.__lang === 'zh' ? '每条摘要并行翻译成中文、日文、德文、葡萄牙文。工具名和 handle 保留英文。' : 'Each summary is translated in parallel into Chinese, Japanese, German and Brazilian Portuguese. Tool names and handles stay in English.' },
            { n: '04', t: window.__lang === 'zh' ? '合成' : 'Synthesize', d: window.__lang === 'zh' ? '每周日把 47 条事件归纳成 2–6 个趋势主题，并生成本周头版总结。' : 'Every Sunday, the week\'s 47 events are clustered into 2–6 trends and condensed into the front-page summary.' },
            { n: '05', t: window.__lang === 'zh' ? '下架' : 'Opt-out',   d: window.__lang === 'zh' ? '任何创业者都可以申请下架。表单提交后 24 小时内移除。' : 'Any builder can request removal. Their profile is taken down within 24 hours of submitting the form.' },
          ].map(step => (
            <div key={step.n} className="flex items-baseline gap-4">
              <span className="num mono" style={{fontSize:14, fontWeight:600, color:'var(--accent)', minWidth:36}}>{step.n}</span>
              <div>
                <h3 className="title-sm mb-2">{step.t}</h3>
                <p style={{margin:0, fontSize:14, lineHeight:1.6, color:'var(--fg-soft)'}}>{step.d}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="hr mt-8 mb-8"/>

        <h2 className="title-lg mb-4">{window.__lang === 'zh' ? '不做什么' : 'What we don\'t do'}</h2>
        <ul className="lede" style={{padding:0, listStyle:'none', display:'grid', gap:12}}>
          {[
            window.__lang === 'zh' ? '不抓取 LinkedIn（合规风险）。' : 'No LinkedIn scraping (compliance risk).',
            window.__lang === 'zh' ? '不私信、不刮取私人内容、不存储任何登录态。' : 'No DMs, no scraping behind logins, no stored credentials.',
            window.__lang === 'zh' ? '不臆测数字。写不出来的数字宁可留空。' : 'No invented numbers. A field stays blank rather than guessing.',
            window.__lang === 'zh' ? '不对任何创业者进行排名或打分。' : 'No ranking or rating of builders as individuals.',
          ].map((line, i) => (
            <li key={i} className="flex items-start gap-3">
              <span style={{marginTop:10, width:5, height:5, borderRadius:3, background:'var(--negative)', flexShrink:0}}/>
              <span>{line}</span>
            </li>
          ))}
        </ul>

        <div className="hr mt-8 mb-6"/>

        <div className="card" style={{padding:'24px 28px'}}>
          <div className="flex items-baseline gap-3 mb-3">
            <div className="ai-strip-dot"/>
            <h3 className="title-sm">{window.__lang === 'zh' ? '受影响？' : 'Affected?'}</h3>
          </div>
          <p style={{margin:0, fontSize:14, lineHeight:1.6, color:'var(--fg-soft)'}}>
            {window.__lang === 'zh'
              ? '如果你是被追踪的创业者、不希望出现在这里，可以一键申请下架，24 小时内处理。'
              : 'If you\'re a tracked builder and don\'t want to be listed, you can request removal in one form — processed within 24 hours.'}
          </p>
          <a className="btn btn-primary mt-4" href="/opt-out">{t('footer_remove')} →</a>
        </div>
      </div>
    </div>
  );
}

// ============= OPT-OUT PAGE ==============================
function OptOutPage() {
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({ email: '', slug: '', reason: '' });

  if (submitted) {
    return (
      <div className="page-enter" style={{padding:'120px 0', textAlign:'center'}}>
        <div className="container-narrow">
          <div style={{width:64, height:64, borderRadius:'50%', background:'var(--positive-soft)', color:'var(--positive)', display:'grid', placeItems:'center', margin:'0 auto 24px'}}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
          </div>
          <h1 className="title-xl mb-4">Request received.</h1>
          <p className="lede" style={{maxWidth:'48ch', margin:'0 auto'}}>
            We've logged your request <span className="mono code">req_{Math.random().toString(36).slice(2,10)}</span> and will process it within 24 hours. You'll receive a confirmation email at <strong>{form.email || 'your address'}</strong>.
          </p>
          <a className="btn mt-8" href="/">← Back to home</a>
        </div>
      </div>
    );
  }

  return (
    <div className="page-enter" style={{padding:'56px 0 80px'}}>
      <div className="container-narrow">
        <div className="eyebrow mb-4">/ opt-out</div>
        <h1 className="title-xl" style={{marginBottom:14}}>{t('optout_heading')}</h1>
        <p className="lede" style={{marginBottom:40, maxWidth:'58ch'}}>{t('optout_intro')}</p>

        <form className="card" style={{padding:'32px'}} onSubmit={e => { e.preventDefault(); setSubmitted(true); }}>
          <FormField label={t('optout_email')} required>
            <input type="email" required value={form.email}
                   onChange={e => setForm({...form, email: e.target.value})}
                   placeholder="you@yourdomain.com"
                   style={inputStyle}/>
          </FormField>
          <FormField label={t('optout_slug')}>
            <div style={{display:'flex', alignItems:'center', border:'1px solid var(--border)', borderRadius:'var(--r-sm)', overflow:'hidden'}}>
              <span className="mono" style={{padding:'10px 12px', background:'var(--bg-sunken)', color:'var(--fg-muted)', fontSize:13, borderRight:'1px solid var(--border)'}}>opc.how/makers/</span>
              <input type="text" value={form.slug}
                     onChange={e => setForm({...form, slug: e.target.value})}
                     placeholder="your-slug"
                     style={{...inputStyle, border:'none', flex:1, paddingLeft:12}}/>
            </div>
          </FormField>
          <FormField label={t('optout_reason')}>
            <textarea rows="3" value={form.reason}
                      onChange={e => setForm({...form, reason: e.target.value})}
                      placeholder="Optional — helps us improve."
                      style={{...inputStyle, resize:'vertical', minHeight:80}}/>
          </FormField>
          <div className="flex items-center gap-4 mt-6">
            <button type="submit" className="btn btn-primary">{t('optout_submit')} →</button>
            <span className="mono faint" style={{fontSize:11}}>{t('optout_eta')}</span>
          </div>
        </form>

        <div className="ai-strip mt-6">
          <span className="ai-strip-dot"/>
          <span>{window.__lang === 'zh'
            ? '我们不需要登录验证。这是基于公开数据的聚合，下架是 ~人工流程~。'
            : 'No login needed. This is a public-data aggregator; opt-out is a human review process.'}</span>
        </div>
      </div>
    </div>
  );
}

function FormField({ label, required, children }) {
  return (
    <div style={{marginBottom:20}}>
      <label className="mono" style={{display:'block', fontSize:12, fontWeight:500, color:'var(--fg)', marginBottom:8, letterSpacing:'0.02em'}}>
        {label}{required && <span style={{color:'var(--accent)', marginLeft:4}}>*</span>}
      </label>
      {children}
    </div>
  );
}

const inputStyle = {
  width:'100%',
  padding:'10px 12px',
  fontSize:14,
  fontFamily:'var(--font-sans)',
  background:'var(--bg)',
  color:'var(--fg)',
  border:'1px solid var(--border)',
  borderRadius:'var(--r-sm)',
  outline:'none',
};

Object.assign(window, { TrendsListPage, TrendDetailPage, ArchiveListPage, ArchiveWeekPage, AboutPage, OptOutPage });
