/* sema ikutoke Collections — Channels & Dashboard */
const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC, useRef: useRefC } = React;

/* ─── channel data ─── */
const CHANNELS = [
  {
    id: "wa",
    name: "WhatsApp Business",
    handle: "+254 712 003 421",
    blurb: "The way most East African shoppers actually buy. Sync your collection to a WhatsApp catalog; buyers DM you and get a checkout link.",
    status: "connected",
    primary: true,
    sales30: "KSh 184,200",
    share: 47,
    accent: "#1B8B53",
    mark: "WA",
    lastSync: "2 min ago",
  },
  {
    id: "ig",
    name: "Instagram Shop",
    handle: "@kamau.studio",
    blurb: "Tag products in posts and stories. Tap-to-buy in feed. Auto-sync from your sema ikutoke collection.",
    status: "connected",
    sales30: "KSh 58,800",
    share: 15,
    accent: "#E14118",
    mark: "IG",
    lastSync: "12 min ago",
  },
  {
    id: "fb",
    name: "Facebook Shop",
    handle: "Kamau Studio",
    blurb: "Discoverable in Facebook Shops & Marketplace. Same catalog, broader audience.",
    status: "connected",
    sales30: "KSh 14,400",
    share: 4,
    accent: "#0E2740",
    mark: "FB",
    lastSync: "1 hr ago",
  },
  {
    id: "tt",
    name: "TikTok Shop",
    handle: "@kamau.studio",
    blurb: "In-video product links. Live shopping. Beta in Kenya, Nigeria & Egypt.",
    status: "needs-attention",
    statusNote: "Verify business",
    sales30: "—",
    share: 0,
    accent: "#161210",
    mark: "TT",
    lastSync: "Awaiting verification",
  },
  {
    id: "jumia",
    name: "Jumia",
    handle: "Pending",
    blurb: "Reach Jumia's marketplace shoppers. Manual approval per category (digital goods only).",
    status: "available",
    sales30: "—",
    share: 0,
    accent: "#F1582E",
    mark: "JU",
    lastSync: "Not connected",
  },
  {
    id: "x",
    name: "X (Twitter)",
    handle: "@kamau.studio",
    blurb: "Drop product cards in your replies. Buyers tap → STK push, no leaving timeline.",
    status: "available",
    sales30: "—",
    share: 0,
    accent: "#161210",
    mark: "X",
    lastSync: "Not connected",
  },
  {
    id: "pin",
    name: "Pinterest",
    handle: "Pending",
    blurb: "Rich product pins. Great for visual collections — photo books, presets, design templates.",
    status: "available",
    sales30: "—",
    share: 0,
    accent: "#C2421A",
    mark: "PI",
    lastSync: "Not connected",
  },
  {
    id: "site",
    name: "sema ikutoke site",
    handle: "kamau.sema-ikutoke.so",
    blurb: "Your home. The shell you built. Where the real catalog lives.",
    status: "connected",
    primary: false,
    sales30: "KSh 130,400",
    share: 34,
    accent: "#5D2BD0",
    mark: "RI",
    lastSync: "Always live",
  },
];

/* ═══════════════════════════════════════════════════════════════════════
   CHANNELS view
   ═══════════════════════════════════════════════════════════════════════ */
function Channels({ goto }) {
  const [focused, setFocused] = useStateC(null);
  const channel = CHANNELS.find((c) => c.id === focused);

  return (
    <div className="view-anim">
      <TopNav goto={goto} view="channels" />
      <div className="gallery">
        <div className="gallery-hd">
          <div>
            <div className="mono" style={{color:"var(--ink-soft)", marginBottom:14}}>§ 03 / Distribution</div>
            <h1>Sell where they <em>already are</em>.</h1>
          </div>
          <p className="h-sub" style={{maxWidth:"40ch", margin:0}}>
            sema ikutoke is your <b>source of truth</b>. Build your collection once — sync it to
            WhatsApp, Instagram, Facebook, TikTok, anywhere your buyers spend time.
            Every sale lands back in M-PESA.
          </p>
        </div>

        <div className="channel-grid">
          {CHANNELS.map((c) => (
            <ChannelCard key={c.id} channel={c} onOpen={() => setFocused(c.id)} />
          ))}
        </div>

        <div className="channel-pipe">
          <div className="pipe-step">
            <div className="pipe-num">01</div>
            <b>One source.</b>
            <p>Your collection in sema ikutoke. Edited once.</p>
          </div>
          <div className="pipe-arrow">→</div>
          <div className="pipe-step">
            <div className="pipe-num">02</div>
            <b>Many surfaces.</b>
            <p>WhatsApp, IG, FB, TikTok, Jumia, X — automatic sync.</p>
          </div>
          <div className="pipe-arrow">→</div>
          <div className="pipe-step">
            <div className="pipe-num">03</div>
            <b>One inbox.</b>
            <p>All sales settle into your M-PESA wallet. Receipts in one place.</p>
          </div>
        </div>
      </div>

      {channel && (
        <ChannelDrawer channel={channel} onClose={() => setFocused(null)} goto={goto} />
      )}
    </div>
  );
}

function ChannelCard({ channel, onOpen }) {
  const c = channel;
  const statusLabel = {
    "connected": "● Connected",
    "needs-attention": "▲ Action needed",
    "available": "+ Connect",
  }[c.status];
  return (
    <div className={"chan-card chan-" + c.status} onClick={onOpen}>
      <div className="chan-head">
        <div className="chan-mark" style={{background: c.accent}}>{c.mark}</div>
        <div style={{flex:1, minWidth:0}}>
          <div className="chan-name">{c.name}</div>
          <div className="chan-handle">{c.handle}</div>
        </div>
        <div className={"chan-status chan-status-" + c.status}>
          {statusLabel}
        </div>
      </div>
      <p className="chan-blurb">{c.blurb}</p>
      <div className="chan-foot">
        <div>
          <span className="mono" style={{color:"var(--ink-faint)"}}>30D REVENUE</span>
          <div className="chan-sales">{c.sales30}</div>
        </div>
        <div style={{textAlign:"right"}}>
          <span className="mono" style={{color:"var(--ink-faint)"}}>LAST SYNC</span>
          <div className="chan-sync">{c.lastSync}</div>
        </div>
      </div>
      {c.share > 0 && (
        <div className="chan-bar"><div style={{width: c.share + "%", background: c.accent}} /></div>
      )}
    </div>
  );
}

function ChannelDrawer({ channel, onClose, goto }) {
  const c = channel;
  const [synced, setSynced] = useStateC(false);
  const [syncing, setSyncing] = useStateC(false);

  const doSync = () => {
    setSyncing(true);
    setTimeout(() => { setSyncing(false); setSynced(true); }, 1600);
  };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer" style={{width: "min(560px, 100vw)"}}>
        <button className="drawer-close" onClick={onClose}>×</button>
        <div className="row-flex" style={{marginBottom: 4}}>
          <div className="chan-mark" style={{background: c.accent, width: 44, height: 44}}>{c.mark}</div>
          <div style={{flex:1}}>
            <h3 style={{fontFamily:"var(--serif)", fontSize:30, fontWeight:400, margin:0, letterSpacing:"-.02em"}}>{c.name}</h3>
            <div className="mono" style={{color:"var(--ink-soft)"}}>{c.handle}</div>
          </div>
        </div>

        {/* WhatsApp gets a chat preview */}
        {c.id === "wa" && (
          <div className="wa-preview">
            <div className="wa-bar">
              <div className="wa-avatar">K</div>
              <div>
                <b>Kamau Studio</b>
                <small>online</small>
              </div>
            </div>
            <div className="wa-thread">
              <div className="wa-msg in">Hi, do you still have Field Notes Vol. 03?</div>
              <div className="wa-msg out">Hi! Yes — here it is 👇</div>
              <div className="wa-msg out wa-product">
                <div className="wa-cover" />
                <div style={{padding:"8px 10px"}}>
                  <b style={{fontFamily:"var(--serif)", fontSize:16}}>Field Notes Vol. 03</b>
                  <div className="mono" style={{color:"var(--ink-soft)", fontSize:10}}>23 photos · 14 essays · 42 MB</div>
                  <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", marginTop:6}}>
                    <span style={{color:"var(--accent)", fontFamily:"var(--serif)", fontSize:18}}>KSh 1,200</span>
                    <span className="chip mint">Buy via M-PESA</span>
                  </div>
                </div>
              </div>
              <div className="wa-msg in">Done — sent! 🎉</div>
            </div>
            <div className="wa-foot">Buyers DM your business number. sema ikutoke's bot shares the catalog and sends a M-PESA STK link.</div>
          </div>
        )}

        <div className="cfg-section">
          <div className="cfg-title">▸ What gets synced</div>
          <div className="cfg-row">
            <span>Collections</span>
            <span className="mono">3 of 3 ▸ Field Notes, Quiet Pages, Embers</span>
          </div>
          <div className="cfg-row">
            <span>Inventory</span>
            <span className="mono">Auto · digital · unlimited</span>
          </div>
          <div className="cfg-row">
            <span>Currency</span>
            <span className="mono">KSh ▸ USD on request</span>
          </div>
          <div className="cfg-row">
            <span>Auto-republish</span>
            <span><b style={{color:"var(--mint)"}}>On</b> · within 60s of edit</span>
          </div>
        </div>

        <div className="cfg-section">
          <div className="cfg-title">▸ Checkout behaviour</div>
          <div className="cfg-row">
            <span>Payment</span>
            <span className="mono">M-PESA · STK push (primary)</span>
          </div>
          <div className="cfg-row">
            <span>Fallback</span>
            <span className="mono">Card · USD payouts</span>
          </div>
          <div className="cfg-row">
            <span>Delivery</span>
            <span className="mono">Instant download · email + DM</span>
          </div>
        </div>

        {c.status !== "available" && (
          <div className="cfg-meta">
            <div>
              <span className="mono" style={{color:"var(--ink-faint)"}}>30D REVENUE</span>
              <div style={{fontFamily:"var(--serif)", fontSize:30, lineHeight:1}}>{c.sales30}</div>
            </div>
            <div style={{textAlign:"right"}}>
              <span className="mono" style={{color:"var(--ink-faint)"}}>SHARE OF SALES</span>
              <div style={{fontFamily:"var(--serif)", fontSize:30, lineHeight:1}}>{c.share}%</div>
            </div>
          </div>
        )}

        <div style={{display:"flex", gap:10, marginTop:"auto", paddingTop:14, borderTop:"1px solid var(--line)"}}>
          {c.status === "available" ? (
            <button className="btn btn-primary btn-lg" style={{flex:1, justifyContent:"center"}}>
              Connect {c.name} <span className="arrow"/>
            </button>
          ) : c.status === "needs-attention" ? (
            <button className="btn btn-primary btn-lg" style={{flex:1, justifyContent:"center"}}>
              Resolve · {c.statusNote} <span className="arrow"/>
            </button>
          ) : (
            <>
              <button className="btn btn-ink btn-lg" onClick={doSync} style={{flex:1, justifyContent:"center"}}>
                {syncing ? "Syncing…" : synced ? "✓ Synced just now" : "Sync now"}
              </button>
              <button className="btn btn-outline" onClick={() => goto("dashboard")}>View sales</button>
            </>
          )}
        </div>
      </div>
    </>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   DASHBOARD view
   ═══════════════════════════════════════════════════════════════════════ */
const SAMPLE_SALES = [
  { who: "Wambui K.", item: "Field Notes Vol. 03", amount: "1,200", channel: "WhatsApp", chMark: "WA", chColor: "#1B8B53", phone: "0712 *** 421" },
  { who: "Mutua O.", item: "Embers · Sample Pack", amount: "2,000", channel: "Instagram", chMark: "IG", chColor: "#E14118", phone: "0721 *** 008" },
  { who: "Achieng' P.", item: "Quiet Pages", amount: "1,200", channel: "sema ikutoke site", chMark: "RI", chColor: "#5D2BD0", phone: "0708 *** 552" },
  { who: "Otieno J.", item: "Field Notes Vol. 03", amount: "1,200", channel: "WhatsApp", chMark: "WA", chColor: "#1B8B53", phone: "0710 *** 014" },
  { who: "Naliaka B.", item: "Atelier 03", amount: "1,800", channel: "Facebook", chMark: "FB", chColor: "#0E2740", phone: "0733 *** 991" },
  { who: "Cheruiyot M.", item: "Field Notes Vol. 03", amount: "1,200", channel: "Instagram", chMark: "IG", chColor: "#E14118", phone: "0701 *** 244" },
  { who: "Wanjiku N.", item: "Embers · Sample Pack", amount: "2,000", channel: "WhatsApp", chMark: "WA", chColor: "#1B8B53", phone: "0719 *** 380" },
  { who: "Said H.", item: "Pasture & Light", amount: "2,400", channel: "sema ikutoke site", chMark: "RI", chColor: "#5D2BD0", phone: "0728 *** 117" },
];

function Dashboard({ goto }) {
  const [feed, setFeed] = useStateC([SAMPLE_SALES[0], SAMPLE_SALES[1], SAMPLE_SALES[2]]);
  const [revenue, setRevenue] = useStateC(46280);
  const [count, setCount] = useStateC(38);

  // Simulated incoming sales
  useEffectC(() => {
    const tick = setInterval(() => {
      const next = SAMPLE_SALES[Math.floor(Math.random() * SAMPLE_SALES.length)];
      const justNow = { ...next, id: Date.now(), justArrived: true };
      setFeed((f) => [justNow, ...f].slice(0, 8));
      setRevenue((r) => r + parseInt(next.amount.replace(/,/g, ""), 10));
      setCount((c) => c + 1);
    }, 4200);
    return () => clearInterval(tick);
  }, []);

  return (
    <div className="view-anim">
      <TopNav goto={goto} view="dashboard" />
      <div className="dash-bar">
        <div>
          <div className="mono" style={{color:"var(--ink-soft)"}}>WORKSPACE</div>
          <div className="row-flex" style={{gap:8}}>
            <div className="chan-mark" style={{width:24, height:24, fontSize:11, background:"var(--ink)"}}>K</div>
            <b style={{fontFamily:"var(--serif)", fontSize:22, fontWeight:400}}>Kamau Studio</b>
            <span className="mono" style={{color:"var(--ink-faint)"}}>· kamau.sema-ikutoke.so</span>
          </div>
        </div>
        <div className="dash-bar-actions">
          <span className="chip mint">● 4 channels live</span>
          <button className="btn btn-outline btn-sm" onClick={() => goto("channels")}>Manage channels</button>
          <button className="btn btn-primary btn-sm" onClick={() => goto("builder")}>Edit collection</button>
        </div>
      </div>

      <div className="dash">
        {/* KPI strip */}
        <div className="kpi-row">
          <div className="kpi">
            <div className="kpi-label">Today</div>
            <div className="kpi-val">KSh {revenue.toLocaleString()}</div>
            <div className="kpi-meta"><span className="mint-up">▲ 23%</span> vs yesterday</div>
          </div>
          <div className="kpi">
            <div className="kpi-label">Sales today</div>
            <div className="kpi-val">{count}</div>
            <div className="kpi-meta">{count > 30 ? "Best day this week" : "Solid pace"}</div>
          </div>
          <div className="kpi">
            <div className="kpi-label">Avg. STK approval</div>
            <div className="kpi-val">11.2<small>s</small></div>
            <div className="kpi-meta">98.4% approval rate</div>
          </div>
          <div className="kpi">
            <div className="kpi-label">In M-PESA wallet</div>
            <div className="kpi-val">KSh 184k</div>
            <div className="kpi-meta"><a className="link-accent">Withdraw to bank →</a></div>
          </div>
        </div>

        {/* Main grid */}
        <div className="dash-grid">
          {/* Sales feed */}
          <div className="dash-card dash-card-tall">
            <div className="dash-card-hd">
              <div>
                <div className="mono" style={{color:"var(--ink-soft)"}}>§ Live feed</div>
                <h3>Sales as they happen.</h3>
              </div>
              <div className="row-flex" style={{gap:8}}>
                <span className="chip mint">● live</span>
              </div>
            </div>
            <div className="feed">
              {feed.map((s, i) => (
                <div key={s.id || i} className={"feed-row " + (s.justArrived ? "fresh" : "")}>
                  <div className="chan-mark" style={{background: s.chColor, width:32, height:32, fontSize:11}}>{s.chMark}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{display:"flex", alignItems:"baseline", gap:8, flexWrap:"wrap"}}>
                      <b>{s.who}</b>
                      <span className="mono" style={{color:"var(--ink-faint)"}}>{s.phone}</span>
                    </div>
                    <div className="muted" style={{fontSize:13}}>
                      bought <i style={{fontStyle:"italic", fontFamily:"var(--serif)"}}>{s.item}</i> via {s.channel}
                    </div>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <div style={{fontFamily:"var(--serif)", fontSize:20}}>KSh {s.amount}</div>
                    <div className="mono" style={{color:"var(--mint)", fontSize:10}}>● paid</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Channel split */}
          <div className="dash-card">
            <div className="dash-card-hd">
              <div>
                <div className="mono" style={{color:"var(--ink-soft)"}}>§ By channel</div>
                <h3>Where they're buying.</h3>
              </div>
            </div>
            <div className="chan-split">
              {[
                { name: "WhatsApp", pct: 47, color: "#1B8B53" },
                { name: "sema ikutoke site", pct: 34, color: "#5D2BD0" },
                { name: "Instagram", pct: 15, color: "#E14118" },
                { name: "Facebook", pct: 4, color: "#0E2740" },
              ].map((r) => (
                <div className="split-row" key={r.name}>
                  <div style={{display:"flex", justifyContent:"space-between", marginBottom:6}}>
                    <span>{r.name}</span>
                    <b style={{fontFamily:"var(--serif)"}}>{r.pct}%</b>
                  </div>
                  <div className="split-bar"><div style={{width: r.pct + "%", background: r.color}} /></div>
                </div>
              ))}
            </div>
            <button className="btn btn-outline btn-sm" style={{justifyContent:"center", marginTop:4}} onClick={() => goto("channels")}>
              Manage channels →
            </button>
          </div>

          {/* Top collections */}
          <div className="dash-card">
            <div className="dash-card-hd">
              <div>
                <div className="mono" style={{color:"var(--ink-soft)"}}>§ Top this week</div>
                <h3>Best sellers.</h3>
              </div>
            </div>
            <div className="top-list">
              {[
                { name: "Field Notes Vol. 03", count: 84, rev: "100,800", g: "linear-gradient(135deg, #E14118, #14110D)" },
                { name: "Embers · Sample Pack", count: 41, rev: "82,000", g: "linear-gradient(135deg, #F1582E, #1B1410)" },
                { name: "Pasture & Light", count: 22, rev: "52,800", g: "linear-gradient(135deg, #1B8B53, #F1E8D1)" },
                { name: "Quiet Pages", count: 64, rev: "0 (free)", g: "linear-gradient(135deg, #5D2BD0, #F4DCD2)" },
              ].map((t, i) => (
                <div key={i} className="top-row">
                  <div className="top-thumb" style={{background: t.g}} />
                  <div style={{flex:1, minWidth:0}}>
                    <b style={{fontFamily:"var(--serif)", fontSize:18, fontWeight:400}}>{t.name}</b>
                    <div className="mono" style={{color:"var(--ink-faint)", fontSize:10}}>{t.count} sales</div>
                  </div>
                  <div className="mono">KSh {t.rev}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Recent buyers map / list */}
          <div className="dash-card dash-card-wide">
            <div className="dash-card-hd">
              <div>
                <div className="mono" style={{color:"var(--ink-soft)"}}>§ Buyers</div>
                <h3>Who showed up this week.</h3>
              </div>
              <button className="btn btn-ghost btn-sm">Export CSV</button>
            </div>
            <div className="buyer-grid">
              {[
                { name: "Wambui K.", city: "Nairobi", first: true, count: 1, total: "1,200" },
                { name: "Mutua O.", city: "Mombasa", first: false, count: 3, total: "5,400" },
                { name: "Achieng' P.", city: "Kisumu", first: true, count: 1, total: "1,200" },
                { name: "Otieno J.", city: "Nairobi", first: false, count: 2, total: "2,400" },
                { name: "Naliaka B.", city: "Eldoret", first: true, count: 1, total: "1,800" },
                { name: "Cheruiyot M.", city: "Nakuru", first: true, count: 1, total: "1,200" },
                { name: "Wanjiku N.", city: "Thika", first: false, count: 4, total: "8,000" },
                { name: "Said H.", city: "Mombasa", first: true, count: 1, total: "2,400" },
              ].map((b, i) => (
                <div key={i} className="buyer-card">
                  <div className="buyer-avatar">{b.name[0]}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <b>{b.name}</b>
                    <div className="mono" style={{color:"var(--ink-faint)"}}>
                      {b.city} {b.first && <span className="chip" style={{background:"var(--accent)", color:"var(--accent-ink)", fontSize:9, padding:"1px 5px", marginLeft:6}}>FIRST</span>}
                    </div>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <div className="mono" style={{fontSize:10, color:"var(--ink-faint)"}}>{b.count}× · KSh {b.total}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Channels, Dashboard, CHANNELS });
