// Order tracking + Reviews wall + Cart

function TrackPage({ go }) {
  const [orderId, setOrderId] = React.useState('');
  const [loaded, setLoaded] = React.useState(null);

  const onLookup = (e) => {
    e?.preventDefault();
    if (!orderId.trim()) return;
    setLoaded({
      id: orderId.trim().toUpperCase(),
      product: PRODUCTS[0],
      variant: '3 Months · Shared',
      status: 'delivered',
      crypto: 'LTC',
      timeline: [
        { t: '14:22:08', label: 'Order created', done: true },
        { t: '14:22:09', label: 'Wallet address generated', done: true },
        { t: '14:23:47', label: 'Payment detected · mempool', done: true },
        { t: '14:26:12', label: 'Confirming · 1/3', done: true },
        { t: '14:28:31', label: 'Confirming · 3/3 · confirmed', done: true },
        { t: '14:28:34', label: 'Fulfillment bot triggered', done: true },
        { t: '14:28:41', label: 'Delivery dispatched to endpoint', done: true },
      ],
    });
  };

  return (
    <section className="max-w-[860px] mx-auto px-5 md:px-8 pt-10 md:pt-16">
      <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-2">Order tracking</div>
      <h1 className="text-4xl md:text-5xl font-semibold tracking-tight">Where's my order?</h1>
      <p className="text-white/55 mt-2 max-w-xl">Paste your order ID. Works for guest checkouts too — we don't require an account to track.</p>

      <form onSubmit={onLookup} className="mt-6 flex gap-2">
        <div className="hairline rounded-xl flex items-center gap-2 px-4 py-3 flex-1 accent-ring">
          <Icon name="search" size={14} />
          <input
            value={orderId}
            onChange={(e) => setOrderId(e.target.value)}
            placeholder="DS-XXXX-XXXX"
            className="bg-transparent outline-none mono text-sm flex-1 min-w-0 uppercase"
          />
        </div>
        <button type="submit" className="btn-primary px-5 text-sm">Track</button>
      </form>

      {!loaded && (
        <div className="mt-6 grid grid-cols-3 gap-2 text-xs text-white/40">
          {['DS-X7KQ-9M2P', 'DS-B3RT-7K9N', 'DS-P4CQ-2H8L'].map(id => (
            <button key={id} onClick={() => { setOrderId(id); setTimeout(() => document.querySelector('form button')?.click(), 100); }} className="hairline rounded-lg px-3 py-2 mono text-left hover:border-white/20">
              try {id}
            </button>
          ))}
        </div>
      )}

      {loaded && (
        <div className="mt-8">
          <div className="glass rounded-2xl p-6">
            <div className="flex items-start gap-4">
              <ProductThumb product={loaded.product} size={56} rounded="rounded-lg" glyphClass="text-2xl" />
              <div className="flex-1">
                <div className="flex items-start justify-between gap-3 flex-wrap">
                  <div>
                    <div className="font-medium">{loaded.product.name} · {loaded.variant}</div>
                    <div className="text-xs text-white/55 mono mt-0.5">{loaded.id} · paid in {loaded.crypto}</div>
                  </div>
                  <Badge tone="ok"><Icon name="check" size={10} /> delivered</Badge>
                </div>
              </div>
            </div>
            <div className="mt-6 pt-6 border-t" style={{ borderColor: 'var(--line)' }}>
              <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-4">Fulfillment log</div>
              <div className="space-y-3">
                {loaded.timeline.map((e, i) => (
                  <div key={i} className="flex items-start gap-3">
                    <div className="w-5 h-5 rounded-full flex items-center justify-center shrink-0 mt-0.5" style={{ background: 'rgba(125,243,161,0.12)', color: 'var(--ok)', border: '1px solid rgba(125,243,161,0.25)' }}>
                      <Icon name="check" size={10} />
                    </div>
                    <div className="flex-1 flex items-center justify-between gap-3 pb-3 border-b last:border-b-0 last:pb-0" style={{ borderColor: 'var(--line)' }}>
                      <span className="text-sm">{e.label}</span>
                      <span className="text-xs mono text-white/40">{e.t}</span>
                    </div>
                  </div>
                ))}
              </div>
              <div className="mt-5 hairline rounded-lg p-3 mono text-xs break-all" style={{ background: 'var(--bg)' }}>
                <div className="text-white/40 mb-1">txid</div>
                <div className="text-white/70">3a8f9c2e7b5d4f1a6c0e2b8d3f5a7c9e1b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a</div>
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

function ReviewsPage() {
  const [filter, setFilter] = React.useState('all');
  const sorted = React.useMemo(() => {
    let list = REVIEWS.slice();
    if (filter === '5') list = list.filter(r => r.rating === 5);
    if (filter === 'low') list = list.filter(r => r.rating <= 3);
    if (filter === 'media') list = list.filter(r => r.hasMedia);
    return list;
  }, [filter]);

  const avg = 4.87;
  const total = 12842;

  return (
    <section className="max-w-[1280px] mx-auto px-5 md:px-8 pt-10 md:pt-16">
      <div className="grid grid-cols-1 md:grid-cols-[1fr_1fr] gap-10 items-end">
        <div>
          <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-2">Trust wall</div>
          <h1 className="text-4xl md:text-5xl font-semibold tracking-tight">Reviews from verified buyers</h1>
          <p className="text-white/55 mt-2 max-w-xl">Every review below is tied to a fulfilled on-chain purchase. Filter by rating, product, or media to see the full picture.</p>
        </div>
        <div className="hairline rounded-2xl p-6 grid grid-cols-3 gap-4" style={{ background: 'var(--bg-1)' }}>
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40">Score</div>
            <div className="text-3xl font-semibold mt-1">{avg}</div>
            <div className="mt-1"><Stars rating={avg} size={12} /></div>
          </div>
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40">Reviews</div>
            <div className="text-3xl font-semibold mt-1">{total.toLocaleString()}</div>
            <div className="text-xs text-white/50 mt-1">100% verified</div>
          </div>
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40">Last 30d</div>
            <div className="text-3xl font-semibold mt-1">+1,241</div>
            <div className="text-xs text-white/50 mt-1">avg 4.9 ★</div>
          </div>
        </div>
      </div>

      <div className="mt-8 flex flex-wrap gap-2">
        {[
          { id: 'all', label: 'All' },
          { id: '5', label: '5-star only' },
          { id: 'low', label: 'Critical (≤3★)' },
          { id: 'media', label: 'With media' },
        ].map(f => (
          <button
            key={f.id}
            onClick={() => setFilter(f.id)}
            className={`hairline rounded-full px-3 py-1.5 text-xs ${filter === f.id ? 'selected' : 'selectable'}`}
            style={filter === f.id ? { borderColor: 'var(--accent)', background: 'rgba(168,123,255,0.06)' } : {}}
          >
            {f.label}
          </button>
        ))}
      </div>

      <div className="mt-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
        {sorted.map(r => {
          const product = PRODUCTS.find(p => p.id === r.product);
          return (
            <div key={r.id} className="hairline rounded-2xl p-5 flex flex-col gap-3" style={{ background: 'var(--bg-1)' }}>
              <div className="flex items-center gap-3">
                <ProductThumb product={product} size={36} rounded="rounded-md" glyphClass="text-sm" />
                <div className="min-w-0">
                  <div className="text-xs font-medium truncate">{product.name}</div>
                  <div className="text-[10px] text-white/50 mono truncate">{r.variant}</div>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <Stars rating={r.rating} size={12} />
                <span className="text-xs mono text-white/40">{r.ago}</span>
              </div>
              <p className="text-sm text-white/75 text-pretty">{r.text}</p>
              <div className="mt-auto pt-3 border-t flex items-center justify-between text-xs" style={{ borderColor: 'var(--line)' }}>
                <span className="mono text-white/55">@{r.user}</span>
                {r.verified && <span className="flex items-center gap-1 text-[10px] mono uppercase tracking-widest" style={{ color: 'var(--ok)' }}><Icon name="check" size={10} /> verified</span>}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function CartPage({ cart, go, onRemove, onCheckout }) {
  if (cart.length === 0) {
    return (
      <section className="max-w-[720px] mx-auto px-5 md:px-8 pt-10 md:pt-16 text-center">
        <div className="w-16 h-16 mx-auto rounded-full flex items-center justify-center hairline mb-4" style={{ background: 'var(--bg-1)' }}>
          <Icon name="cart" size={24} />
        </div>
        <h1 className="text-3xl font-semibold tracking-tight">Your cart is empty</h1>
        <p className="text-white/55 mt-2">Digital goods don't take up space — but yours is empty anyway.</p>
        <button onClick={() => go('catalog')} className="btn-primary px-5 py-3 text-sm mt-6 inline-flex items-center gap-2">
          Browse catalog <Icon name="arrow" size={14} />
        </button>
      </section>
    );
  }
  const total = cart.reduce((sum, it) => sum + it.variant.price, 0);
  return (
    <section className="max-w-[1280px] mx-auto px-5 md:px-8 pt-10 md:pt-12 grid grid-cols-1 lg:grid-cols-[1fr_360px] gap-8">
      <div>
        <h1 className="text-3xl font-semibold tracking-tight mb-6">Cart</h1>
        <div className="space-y-3">
          {cart.map((it, i) => (
            <div key={i} className="hairline rounded-xl p-4 flex items-center gap-4" style={{ background: 'var(--bg-1)' }}>
              <ProductThumb product={it.product} size={48} rounded="rounded-md" glyphClass="text-xl" />
              <div className="flex-1 min-w-0">
                <div className="font-medium truncate">{it.product.name}</div>
                <div className="text-xs text-white/55 truncate">{it.variant.label}</div>
              </div>
              <div className="text-right">
                <div className="font-medium mono">{formatUSD(it.variant.price)}</div>
                <button onClick={() => onRemove(i)} className="text-xs text-white/40 hover:text-white mt-1">remove</button>
              </div>
            </div>
          ))}
        </div>
      </div>
      <aside>
        <div className="glass rounded-2xl p-5 lg:sticky lg:top-24">
          <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Summary</div>
          <div className="flex items-baseline justify-between mb-1">
            <span>Total</span>
            <span className="text-2xl font-semibold mono">{formatUSD(total)}</span>
          </div>
          <div className="text-xs text-white/50 mono">≈ {(total / 142.08).toFixed(4)} SOL</div>
          <button onClick={() => onCheckout(cart[0])} className="btn-primary w-full py-3.5 mt-5 inline-flex items-center justify-center gap-2">
            Checkout with crypto <Icon name="arrow" size={14} />
          </button>
          <div className="mt-4 text-xs text-white/50 space-y-1.5">
            <div className="flex items-center gap-2"><Icon name="lock" size={12} /> No account required</div>
            <div className="flex items-center gap-2"><Icon name="bolt" size={12} /> Avg fulfillment 2m 47s</div>
          </div>
        </div>
      </aside>
    </section>
  );
}

Object.assign(window, { TrackPage, ReviewsPage, CartPage });
