/* Listing pages — All phones / Latest / Upcoming / Rumors / Discontinued */

const LISTING_CONTENT = {
  'all': {
    eyebrow: 'Phones · The complete index',
    title: 'All 12,847 phones',
    subtitle: 'The complete searchable database, from current flagships back to the original release of every model we track.',
    badge: null,
    sort: 'release',
  },
  'latest': {
    eyebrow: 'Phones · Latest releases',
    title: 'Released in the last 90 days',
    subtitle: '42 phones launched globally in the last 90 days. Sorted by release date — newest first.',
    badge: 'NEW',
    sort: 'release',
  },
  'upcoming': {
    eyebrow: 'Phones · Confirmed upcoming',
    title: 'Coming in the next 90 days',
    subtitle: 'Phones with confirmed launch dates from manufacturers. Specs preliminary; we re-verify within 24 hours of launch.',
    badge: 'SOON',
    sort: 'release',
  },
  'rumors': {
    eyebrow: 'Phones · Rumored & leaked',
    title: 'Rumored & leaked',
    subtitle: 'Phones that have not been announced but are credible based on supply-chain leaks, certifications, or trusted reporting. Confidence indicated per row.',
    badge: 'LEAK',
    sort: 'rumor',
  },
  'discontinued': {
    eyebrow: 'Phones · Discontinued',
    title: 'No longer in production',
    subtitle: 'Phones removed from manufacturer catalogs. Still serviceable; still researchable — and often still excellent secondhand buys.',
    badge: 'EOL',
    sort: 'release',
  },
};

/* Phone catalog (small, representative). Each item has a `status` flag. */
const CATALOG = [
  // Latest (released ≤90d)
  { name: 'iPhone 16 Pro Max',  brand: 'Apple',    price: '$1,199', spec: '6.9" · A18 Pro · 4685 mAh',         release: 'Sep 2025', status: 'latest',     score: 91, hero: true },
  { name: 'Galaxy S25 Ultra',   brand: 'Samsung',  price: '$1,299', spec: '6.9" · SD 8 Elite · 5000 mAh',      release: 'Feb 2025', status: 'latest',     score: 90 },
  { name: 'Pixel 9 Pro XL',     brand: 'Google',   price: '$1,099', spec: '6.8" · Tensor G4 · 5060 mAh',       release: 'Aug 2025', status: 'latest',     score: 88 },
  { name: 'Xiaomi 15 Ultra',    brand: 'Xiaomi',   price: '$1,499', spec: '6.73" · SD 8 Elite · 6000 mAh',     release: 'Mar 2025', status: 'latest',     score: 87 },
  { name: 'OnePlus 13',         brand: 'OnePlus',  price: '$899',   spec: '6.82" · SD 8 Elite · 6000 mAh',     release: 'Jan 2025', status: 'latest',     score: 87 },
  { name: 'Honor Magic 7 Pro',  brand: 'Honor',    price: '$1,099', spec: '6.8" · SD 8 Elite · 5850 mAh',      release: 'Jan 2025', status: 'latest',     score: 85 },
  { name: 'Nothing Phone 3',    brand: 'Nothing',  price: '$799',   spec: '6.7" · SD 8s Gen 3 · 5150 mAh',     release: 'Jul 2025', status: 'latest',     score: 81 },
  // Upcoming (announced; not shipping yet)
  { name: 'Pixel 10 Pro',       brand: 'Google',   price: 'TBA',    spec: '6.3" · Tensor G5 · spec TBA',       release: 'Aug 2026', status: 'upcoming',   score: null, confirmed: true, eta: '~Aug 14' },
  { name: 'iPhone 17 Air',      brand: 'Apple',    price: 'TBA',    spec: '6.6" · A19 · ultra-thin chassis',   release: 'Sep 2026', status: 'upcoming',   score: null, confirmed: true, eta: '~Sep 9' },
  { name: 'Galaxy Z Fold7',     brand: 'Samsung',  price: '$1,999', spec: '8.0" inner · SD 8 Elite 2',         release: 'Jul 2026', status: 'upcoming',   score: null, confirmed: true, eta: '~Jul 10' },
  { name: 'Xiaomi 16 Pro',      brand: 'Xiaomi',   price: '$899',   spec: '6.7" · SD 8 Elite · Leica APO',     release: 'Oct 2026', status: 'upcoming',   score: null, confirmed: true, eta: '~Oct 25' },
  // Rumors (not announced)
  { name: 'Galaxy S26 Ultra',   brand: 'Samsung',  price: 'TBA',    spec: 'Titanium · "no S Pen" prototype',   release: 'Q1 2027',  status: 'rumors',     score: null, confidence: 'High',   source: 'ETNews · CAD leaks · prototype seen at distributor' },
  { name: 'iPhone Fold',        brand: 'Apple',    price: 'TBA',    spec: '7.8" book · crease-less hinge',     release: 'H2 2027',  status: 'rumors',     score: null, confidence: 'Medium', source: 'Kuo · supply-chain · panel orders' },
  { name: 'Pixel Fold 2',       brand: 'Google',   price: 'TBA',    spec: '7.6" · Tensor G5',                  release: 'H2 2026',  status: 'rumors',     score: null, confidence: 'Medium', source: 'AOSP commits · benchmark leaks' },
  { name: 'OnePlus Open 2',     brand: 'OnePlus',  price: 'TBA',    spec: '8.0" book · ultra-light hinge',     release: 'Q1 2027',  status: 'rumors',     score: null, confidence: 'Low',    source: 'Weibo · single-source' },
  // Discontinued
  { name: 'iPhone 13 mini',     brand: 'Apple',    price: '—',      spec: '5.4" · A15 · 2406 mAh',             release: 'Sep 2021', status: 'discontinued', score: 78, eolDate: 'Oct 2024' },
  { name: 'Galaxy Note 20 Ultra', brand: 'Samsung',price: '—',      spec: '6.9" · SD 865+ · 4500 mAh',         release: 'Aug 2020', status: 'discontinued', score: 75, eolDate: 'Aug 2022' },
  { name: 'Sony Xperia 1 III',  brand: 'Sony',     price: '—',      spec: '6.5" · SD 888 · 4500 mAh',          release: 'Jul 2021', status: 'discontinued', score: 73, eolDate: 'Mar 2023' },
  { name: 'LG Velvet',          brand: 'LG',       price: '—',      spec: '6.8" · SD 765G · 4300 mAh',         release: 'May 2020', status: 'discontinued', score: 64, eolDate: 'Apr 2021' },
  { name: 'BlackBerry Key2',    brand: 'BlackBerry', price: '—',    spec: '4.5" · SD 660 · QWERTY',            release: 'Jul 2018', status: 'discontinued', score: 60, eolDate: 'Feb 2020' },
];

const ListingPage = ({ kind, setPage }) => {
  const meta = LISTING_CONTENT[kind] || LISTING_CONTENT.all;
  const [view, setView] = useState('grid');
  const [brand, setBrand] = useState('all');

  let phones;
  if (kind === 'all') phones = CATALOG;
  else phones = CATALOG.filter((p) => p.status === kind);

  const brandFacets = ['all', ...new Set(phones.map((p) => p.brand))];
  if (brand !== 'all') phones = phones.filter((p) => p.brand === brand);

  const isRumors = kind === 'rumors';
  const isUpcoming = kind === 'upcoming';
  const isDisc = kind === 'discontinued';

  const confidenceTone = (c) => ({
    High:   'text-win bg-win/10 border-win/20',
    Medium: 'text-amber-brand dark:text-amber-warm bg-amber-brand/10 dark:bg-amber-warm/10 border-amber-brand/20 dark:border-amber-warm/20',
    Low:    'text-ink-soft dark:text-d-muted bg-paper-soft dark:bg-d-bg border-line dark:border-d-border',
  }[c] || '');

  return (
    <main className="pb-32">
      {/* Hero */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 pt-12 sm:pt-16">
        <SectionEyebrow>{meta.eyebrow}</SectionEyebrow>
        <SectionTitle size="xxl" className="mt-3">{meta.title}</SectionTitle>
        <p className="mt-5 max-w-2xl text-[15px] sm:text-[16px] leading-relaxed text-ink-soft dark:text-d-muted">
          {meta.subtitle}
        </p>

        <div className="mt-8 flex flex-wrap items-center gap-3 text-[11px] font-mono uppercase tracking-wider text-ink-soft dark:text-d-muted">
          <span className="inline-flex items-center gap-1.5">
            <span className={`h-1.5 w-1.5 rounded-full ${isRumors ? 'bg-ink-soft' : isUpcoming ? 'bg-amber-brand dark:bg-amber-warm' : isDisc ? 'bg-ink-soft/50' : 'bg-win'}`} />
            <span className="num text-ink dark:text-white">{phones.length}</span> {kind === 'all' ? 'phones total (sample of 12,847)' : 'matches'}
          </span>
          <span className="opacity-40">·</span>
          <span className="inline-flex items-center gap-1"><IconRefresh size={11} /> Updated {kind === 'rumors' ? 'as new info surfaces' : 'daily'}</span>
        </div>
      </section>

      {/* Filters */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 mt-10 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2 overflow-x-auto no-scrollbar">
          {brandFacets.map((b) => (
            <button
              key={b}
              onClick={() => setBrand(b)}
              className={`px-3 py-1.5 rounded-full text-[12px] font-medium border whitespace-nowrap transition ${
                brand === b
                  ? 'bg-ink text-white border-ink dark:bg-white dark:text-ink dark:border-white'
                  : 'border-line dark:border-d-border bg-paper dark:bg-d-surface text-ink-soft dark:text-d-muted hover:text-ink dark:hover:text-white'
              }`}
            >
              {b === 'all' ? 'All brands' : b}
            </button>
          ))}
        </div>
        <div className="flex items-center rounded-md border border-line dark:border-d-border bg-paper dark:bg-d-surface p-0.5">
          {[
            { k: 'grid', label: 'Grid' },
            { k: 'list', label: 'List' },
          ].map((v) => (
            <button
              key={v.k}
              onClick={() => setView(v.k)}
              className={`px-2.5 py-1 text-[11px] font-mono uppercase tracking-wider rounded ${
                view === v.k
                  ? 'bg-ink text-white dark:bg-white dark:text-ink'
                  : 'text-ink-soft dark:text-d-muted'
              }`}
            >
              {v.label}
            </button>
          ))}
        </div>
      </section>

      {/* Results */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 mt-6">
        {view === 'grid' ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
            {phones.map((p, i) => (
              <button
                key={i}
                onClick={() => setPage('phones')}
                className="group text-left rounded-2xl border border-line dark:border-d-border bg-paper dark:bg-d-surface p-4 hover:border-amber-brand/40 dark:hover:border-amber-warm/40 transition relative"
              >
                {meta.badge && (
                  <div className={`absolute top-3 left-3 inline-flex items-center rounded-sm px-1.5 py-0.5 text-[9px] font-mono uppercase tracking-wider ${
                    meta.badge === 'NEW' ? 'bg-amber-brand text-white dark:bg-amber-warm dark:text-ink' :
                    meta.badge === 'SOON' ? 'bg-ink text-white dark:bg-white dark:text-ink' :
                    meta.badge === 'LEAK' ? 'bg-navy text-white dark:bg-d-muted dark:text-ink' :
                    'bg-paper-soft dark:bg-d-bg text-ink-soft dark:text-d-muted border border-line dark:border-d-border'
                  }`}>
                    {meta.badge}
                  </div>
                )}
                <div className="flex justify-center py-3">
                  <PhoneRender size="md" tint={i % 3 === 0 ? 'amber' : i % 3 === 1 ? 'navy' : 'neutral'} />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-[10px] font-mono uppercase tracking-wider text-ink-soft dark:text-d-muted">{p.brand}</span>
                  {p.score && <ScorePill value={p.score} label="" tone="outline" />}
                </div>
                <div className="mt-1.5 font-display font-semibold tracking-tighter2 text-[14px] text-ink dark:text-white group-hover:text-amber-brand dark:group-hover:text-amber-warm leading-snug">{p.name}</div>
                <div className="num text-[11px] text-ink-soft dark:text-d-muted">{p.spec}</div>
                <div className="mt-3 pt-3 border-t border-line dark:border-d-border flex items-center justify-between">
                  <span className="num text-[12px] text-ink-soft dark:text-d-muted">
                    {isUpcoming && p.eta ? p.eta : isDisc ? `EOL ${p.eolDate}` : p.release}
                  </span>
                  <span className="num text-[13px] font-semibold text-ink dark:text-white">{p.price}</span>
                </div>
                {isRumors && p.confidence && (
                  <div className={`mt-2 inline-flex items-center gap-1 rounded-sm border px-1.5 py-0.5 text-[10px] font-mono uppercase tracking-wider ${confidenceTone(p.confidence)}`}>
                    {p.confidence} confidence
                  </div>
                )}
              </button>
            ))}
          </div>
        ) : (
          <div className="rounded-2xl border border-line dark:border-d-border bg-paper dark:bg-d-surface overflow-hidden">
            <div className="hidden md:grid grid-cols-12 gap-3 px-5 py-2.5 bg-paper-soft dark:bg-d-bg/50 border-b border-line dark:border-d-border text-[10px] font-mono uppercase tracking-[0.16em] text-ink-soft dark:text-d-muted">
              <div className="col-span-3">Phone</div>
              <div className="col-span-4">Spec</div>
              <div className="col-span-2">{isUpcoming ? 'ETA' : isRumors ? 'Confidence' : isDisc ? 'EOL' : 'Released'}</div>
              <div className="col-span-1 text-right">Score</div>
              <div className="col-span-2 text-right">Price</div>
            </div>
            {phones.map((p, i) => (
              <button
                key={i}
                onClick={() => setPage('phones')}
                className="w-full grid grid-cols-1 md:grid-cols-12 gap-3 px-5 py-3 items-center border-b border-line dark:border-d-border last:border-b-0 hover:bg-paper-soft dark:hover:bg-d-bg transition text-left"
              >
                <div className="md:col-span-3">
                  <div className="text-[10px] font-mono uppercase tracking-wider text-ink-soft dark:text-d-muted">{p.brand}</div>
                  <div className="font-display font-semibold tracking-tighter2 text-[14px] text-ink dark:text-white">{p.name}</div>
                </div>
                <div className="md:col-span-4 num text-[12px] text-ink-soft dark:text-d-muted">{p.spec}</div>
                <div className="md:col-span-2 text-[12px] font-mono uppercase tracking-wider text-ink-soft dark:text-d-muted">
                  {isUpcoming && p.eta ? p.eta : isRumors ? (
                    <span className={`inline-flex items-center rounded-sm border px-1.5 py-0.5 ${confidenceTone(p.confidence)}`}>{p.confidence}</span>
                  ) : isDisc ? p.eolDate : p.release}
                </div>
                <div className="md:col-span-1 md:text-right num text-[14px] font-semibold text-ink dark:text-white">{p.score || '—'}</div>
                <div className="md:col-span-2 md:text-right num text-[13px] font-semibold text-ink dark:text-white">{p.price}</div>
              </button>
            ))}
          </div>
        )}

        {/* Footnote */}
        {isRumors && (
          <div className="mt-8 rounded-2xl border border-line dark:border-d-border bg-paper-soft dark:bg-d-surface p-5">
            <div className="text-[10px] font-mono uppercase tracking-[0.16em] text-ink-soft dark:text-d-muted">Source confidence</div>
            <p className="mt-2 text-[13px] leading-relaxed text-ink dark:text-white max-w-3xl">
              <span className="font-semibold">High</span> means at least two independent sources (one supply-chain, one editorial) plus a regulatory or certification footprint. <span className="font-semibold">Medium</span> means a single trusted source with corroborating signal. <span className="font-semibold">Low</span> means a single-source leak we publish for completeness, with the same trust we'd give Reddit.
            </p>
          </div>
        )}
        {isDisc && (
          <div className="mt-8 rounded-2xl border border-line dark:border-d-border bg-paper-soft dark:bg-d-surface p-5">
            <div className="text-[10px] font-mono uppercase tracking-[0.16em] text-ink-soft dark:text-d-muted">Buying a discontinued phone?</div>
            <p className="mt-2 text-[13px] leading-relaxed text-ink dark:text-white max-w-3xl">
              We keep these pages up because secondhand markets thrive on them — and a phone being EOL doesn't mean it's not the right phone for you. Always check security-patch status before you buy; we surface the manufacturer's last patch date in every discontinued spec sheet.
            </p>
          </div>
        )}
      </section>
    </main>
  );
};

Object.assign(window, { ListingPage });
