// assets/screen_store_detail.jsx
function ScreenStoreDetail({ id, go }) {
  const store = STORES.find(s => s.id === id) || STORES.find(s => s.id.startsWith(id)) || STORES[0];
  const owner = USERS.find(u => u.id === store.owner_user_id) || USERS[0];
  const balance = BALANCES[owner.id]; // may be undefined
  const merchant = MERCHANTS.find(m => m.id === store.merchant_id);
  const otherStores = STORES.filter(s => s.merchant_id === store.merchant_id && s.id !== store.id).slice(0, 5);
  const orders = React.useMemo(() => mkOrdersForStore(store, 10), [store.id]);
  const projects = React.useMemo(() => mkProjectsForMerchant(merchant?.id, store.project_count), [store.id]);
  const projectsCostCents = projects.reduce((s, p) => s + p.total_cost_cents, 0);

  const platBadge = (
    <Badge kind="neutral">
      <span style={{ width: 6, height: 6, background: store.platform_color, borderRadius: '50%' }} />
      {store.platform}
    </Badge>
  );

  const planBadge = !store.plan ? <Badge kind="neutral">No subscription</Badge> :
    <Badge kind={store.plan === 'max' ? 'accent' : store.plan === 'pro' ? 'info' : 'neutral'}>{store.plan[0].toUpperCase() + store.plan.slice(1)}</Badge>;

  return (
    <div className="page">
      {/* Hero header */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 14, alignItems: 'flex-start' }}>
        <div style={{ width: 56, height: 56, borderRadius: 12, background: 'linear-gradient(135deg, ' + store.platform_color + ', var(--bg-active))', display: 'grid', placeItems: 'center', fontSize: 20, fontWeight: 700, color: 'var(--text-primary)', flexShrink: 0 }}>
          {store.name.split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase()}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>{store.name}</h1>
            {platBadge}
            {planBadge}
            {store.subscription_status && <Badge kind={store.subscription_status === 'active' ? 'success' : store.subscription_status === 'past_due' ? 'warning' : 'danger'} dot>{store.subscription_status}</Badge>}
          </div>
          <div style={{ display: 'flex', gap: 14, fontSize: 12, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
            <span><span className="dim">domain</span> <a href="#" className="text-accent"><Mono>{store.store_domain}</Mono></a></span>
            <span><span className="dim">id</span> <Mono dim>{store.id}</Mono></span>
            <span><span className="dim">merchant</span> {store.merchant_name}</span>
            <span><span className="dim">currency</span> <Mono>{store.currency}</Mono></span>
            <span><span className="dim">created</span> <Mono>{fmtDate(store.created_at)}</Mono></span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <a href="#/stores" className="btn ghost"><Icon name="chevron" size={13} style={{ transform: 'rotate(180deg)' }} /> All stores</a>
          <button className="btn"><Icon name="external" size={12} /> Visit storefront</button>
          <button className="btn"><Icon name="copy" size={12} /> Copy store id</button>
        </div>
      </div>

      {/* Metric cards */}
      <div className="grid cols-4" style={{ marginBottom: 14 }}>
        <KpiCard label="Total revenue" value={fmtMoneyCompact(store.revenue_cents)} icon="cost" />
        <div className="card kpi">
          <div className="kpi-label"><Icon name="check2" size={12} /> Total orders</div>
          <div className="kpi-value">{store.total_orders.toLocaleString()}</div>
          <div style={{ marginTop: 6, fontSize: 11, fontFamily: 'var(--font-mono)' }}>
            <span className="text-success">{store.fulfilled_orders} fulfilled</span>
            <span className="dim" style={{ margin: '0 6px' }}>·</span>
            <span className="text-warning">{store.processing_orders} processing</span>
            <span className="dim" style={{ margin: '0 6px' }}>·</span>
            <span className="text-danger">{store.cancelled_orders} cancelled</span>
          </div>
        </div>
        <KpiCard label="Project cost (AI)" value={fmtMoney(projectsCostCents)} icon="zap" />
        <div className="card kpi">
          <div className="kpi-label"><Icon name="trend" size={12} /> Subscription</div>
          <div className="kpi-value" style={{ fontSize: 18 }}>
            {store.plan ? store.plan[0].toUpperCase() + store.plan.slice(1) : 'None'}
            <span className="unit"> · {store.subscription_status || '—'}</span>
          </div>
          <div className="kpi-delta neutral mono">
            {store.plan_price_cents > 0 ? fmtMoney(store.plan_price_cents) + '/mo' : 'no recurring'}
          </div>
        </div>
      </div>

      {/* 3-col layout: left (orders, projects), right (owner, balance, store/merchant/subscription info) */}
      <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
        <div className="flex col gap-3" style={{ gap: 12, minWidth: 0 }}>
          {/* Recent orders */}
          <div className="card">
            <div className="card-head">
              <h3>Recent orders</h3>
              <span className="sub">latest 10</span>
              <div className="actions"><button className="btn xs">View all <Icon name="arrowR" size={11} /></button></div>
            </div>
            <div className="card-body flush">
              <table className="tbl">
                <thead><tr>
                  <th>Order</th><th>Status</th><th>Tracking</th><th className="num">Price</th><th>Created</th><th>ID</th>
                </tr></thead>
                <tbody>
                  {orders.map(o => (
                    <tr key={o.id}>
                      <td><Mono>{o.order_number}</Mono></td>
                      <td>
                        <Badge kind={o.status_code === 2 ? 'success' : o.status_code === 1 ? 'warning' : 'danger'} dot>
                          {o.status}
                        </Badge>
                      </td>
                      <td className="dim2">{o.tracking ? <Mono>{o.tracking}</Mono> : <span className="dim">—</span>}</td>
                      <td className="num"><Mono>{fmtMoney(o.price_cents, o.currency)}</Mono></td>
                      <td className="dim"><Mono>{fmtDate(o.created_at)}</Mono></td>
                      <td className="id">{shortId(o.id, 10)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Projects */}
          <div className="card">
            <div className="card-head">
              <h3>Merchant projects</h3>
              <span className="sub">{projects.length} · {fmtMoney(projectsCostCents)} total AI cost</span>
            </div>
            <div className="card-body flush">
              <table className="tbl">
                <thead><tr>
                  <th>Project</th><th>Status</th><th>Preview</th><th>Production</th><th>Published</th><th>Created</th><th className="num">AI cost</th>
                </tr></thead>
                <tbody>
                  {projects.map(p => (
                    <tr key={p.id}>
                      <td><span style={{ color: 'var(--text-primary)' }}>{p.name}</span><br /><span className="dim mono fs-11">{shortId(p.id, 10)}</span></td>
                      <td><Badge kind={p.status === 'published' ? 'success' : p.status === 'archived' ? 'neutral' : 'warning'}>{p.status}</Badge></td>
                      <td className="dim2"><a href="#" className="text-accent"><Mono>{shortId(p.preview_url.split('/').pop(), 12)}</Mono></a></td>
                      <td className="dim2">{p.production_url ? <a href="#" className="text-accent"><Mono>{shortId(p.production_url.split('/').pop(), 12)}</Mono></a> : '—'}</td>
                      <td>{p.is_published ? <Badge kind="success">live</Badge> : <span className="dim fs-11">—</span>}</td>
                      <td className="dim"><Mono>{fmtDate(p.created_at)}</Mono></td>
                      <td className="num"><Mono>{fmtMoney(p.total_cost_cents)}</Mono></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Store info */}
          <div className="card">
            <div className="card-head"><h3>Store info</h3></div>
            <div className="card-body">
              <KVGrid pairs={[
                ['name', store.name],
                ['domain', <Mono key="d">{store.store_domain}</Mono>],
                ['platform', platBadge],
                ['currency', <Mono key="c">{store.currency}</Mono>],
                ['trd_store_id', store.trd_store_id ? <Mono key="t">{store.trd_store_id}</Mono> : <span className="dim">—</span>],
                ['trd_store_name', store.trd_store_name || <span className="dim">—</span>],
                ['trd_store_domain', store.trd_store_domain ? <Mono key="td">{store.trd_store_domain}</Mono> : <span className="dim">—</span>],
                ['created', <Mono key="c2">{fmtDate(store.created_at)}</Mono>],
                ['updated', <Mono key="u">{fmtDate(store.updated_at)}</Mono>],
                ['store id', <Mono key="i" dim>{store.id}</Mono>],
              ]} />
            </div>
          </div>
        </div>

        {/* Right column */}
        <div className="flex col gap-3" style={{ gap: 12, minWidth: 0 }}>
          {/* Owner */}
          <div className="card">
            <div className="card-head"><h3>Owner</h3></div>
            <div className="card-body">
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <UserAvatar username={owner.username} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13.5 }}>{owner.username}</div>
                  <div className="dim mono fs-11">{owner.email}</div>
                </div>
                <button className="btn xs" onClick={() => go('/users/' + owner.id)}>
                  <Icon name="user" size={11} /> View
                </button>
              </div>
              <KVGrid pairs={[
                ['username', <Mono key="u">{owner.username}</Mono>],
                ['email', <a key="e" href={'mailto:' + owner.email} className="text-accent"><Mono>{owner.email}</Mono></a>],
                ['user id', <Mono key="i" dim>{owner.id}</Mono>],
                ['merchant id', <Mono key="m" dim>{store.merchant_id}</Mono>],
              ]} />
            </div>
          </div>

          {/* Account balance */}
          {balance && (
            <div className="card">
              <div className="card-head"><h3>Account balance</h3><span className="sub">in cents · ÷100 = USD</span></div>
              <div className="card-body">
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 12 }}>
                  <span style={{ fontSize: 22, fontWeight: 600, fontFamily: 'var(--font-mono)', color: balance.total_balance_cents >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                    {fmtMoney(balance.total_balance_cents)}
                  </span>
                  <span className="dim fs-11">total balance</span>
                </div>
                <KVGrid pairs={[
                  ['available', <Mono key="a">{fmtMoney(balance.available_cents)}</Mono>],
                  ['frozen', <Mono key="f" style={{ color: balance.frozen_cents > 0 ? 'var(--warning)' : undefined }}>{fmtMoney(balance.frozen_cents)}</Mono>],
                  ['total deposit', <Mono key="d" className="dim">{fmtMoney(balance.total_deposit_cents)}</Mono>],
                  ['total spend', <Mono key="s" className="dim">{fmtMoney(balance.total_spend_cents)}</Mono>],
                ]} />
              </div>
            </div>
          )}

          {/* Merchant info */}
          <div className="card">
            <div className="card-head"><h3>Merchant</h3></div>
            <div className="card-body">
              <KVGrid pairs={[
                ['name', merchant?.name || '—'],
                ['status', <Badge key="st" kind={merchant?.status === 'active' ? 'success' : 'neutral'} dot>{merchant?.status}</Badge>],
                ['created', <Mono key="c">{fmtDate(merchant?.created_at)}</Mono>],
                ['id', <Mono key="i" dim>{store.merchant_id}</Mono>],
              ]} />
            </div>
          </div>

          {/* Subscription info */}
          {store.subscription_status && (
            <div className="card">
              <div className="card-head"><h3>Subscription</h3></div>
              <div className="card-body">
                <KVGrid pairs={[
                  ['plan', planBadge],
                  ['status', <Badge key="ss" kind={store.subscription_status === 'active' ? 'success' : 'warning'} dot>{store.subscription_status}</Badge>],
                  ['provider', <Mono key="p">{store.subscription_provider}</Mono>],
                  ['stripe customer', <Mono key="sc" dim>{store.stripe_customer_id}</Mono>],
                  ['stripe sub', <Mono key="sb" dim>{store.stripe_sub_id}</Mono>],
                  ['period', <Mono key="pp">{fmtDate(store.period_start)} → {fmtDate(store.period_end)}</Mono>],
                  ['cancel at period end', store.cancel_at_period_end ? <Badge key="ce" kind="warning">yes</Badge> : <span key="ce2" className="dim fs-11">no</span>],
                  ['monthly', <Mono key="m" style={{ fontWeight: 600 }}>{fmtMoney(store.plan_price_cents)}</Mono>],
                ]} />
              </div>
            </div>
          )}

          {/* Other stores */}
          {otherStores.length > 0 && (
            <div className="card">
              <div className="card-head"><h3>Other stores by {merchant?.name}</h3><span className="sub">{otherStores.length}</span></div>
              <div className="card-body flush">
                <table className="tbl">
                  <tbody>
                    {otherStores.map(s => (
                      <tr key={s.id} className="clickable" onClick={() => go('/stores/' + s.id)}>
                        <td>{s.name}<br /><span className="dim mono fs-11">{s.store_domain}</span></td>
                        <td><Badge kind="neutral">{s.platform}</Badge></td>
                        <td className="num"><Mono>{fmtMoneyCompact(s.revenue_cents)}</Mono></td>
                        <td><Icon name="chevron" size={12} className="dim" /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Tiny KV grid helper — used a lot here
function KVGrid({ pairs }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '6px 14px', fontSize: 12 }}>
      {pairs.map(([k, v], i) => (
        <React.Fragment key={i}>
          <span style={{ color: 'var(--text-tertiary)', textTransform: 'uppercase', fontSize: 10.5, letterSpacing: '.04em', fontWeight: 500, paddingTop: 2 }}>{k}</span>
          <span style={{ color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v}</span>
        </React.Fragment>
      ))}
    </div>
  );
}

function UserAvatar({ username, size = 28 }) {
  // gradient seeded from username
  const h1 = [...(username || 'u')].reduce((s, c) => s + c.charCodeAt(0), 0) % 360;
  const h2 = (h1 + 80) % 360;
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', background: `linear-gradient(135deg, oklch(0.62 0.16 ${h1}), oklch(0.42 0.18 ${h2}))`, display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: size * 0.42, color: 'white', flexShrink: 0, fontFamily: 'var(--font-mono)' }}>
      {(username || '?').slice(0, 2).toUpperCase()}
    </div>
  );
}

Object.assign(window, { ScreenStoreDetail, KVGrid, UserAvatar });
