/* =========================================================
   Tappt — Customise nav (Pro): pick bottom-bar slots + radial
   actions, saved per persona. Loaded after app-dash.jsx.
   ========================================================= */
const { useState: ncUse, useEffect: ncEffect } = React;

function NavCustomizeSheet({ user, onClose, onSave, toast }) {
  const POOL = window.NAV_POOL, RPOOL = window.RADIAL_POOL;
  const cfg = window.navCfg(user);
  const persona = window.activePersona ? window.activePersona(user) : { label: 'Profile' };
  const [bar, setBar] = ncUse(cfg.bar.slice());
  const [radial, setRadial] = ncUse(cfg.radial.slice());

  const barPool = Object.keys(POOL);
  const radPool = Object.keys(RPOOL);

  const toggleBar = (id) => {
    if (bar.includes(id)) { if (bar.length <= 2) { toast && toast('Keep at least 2 tabs'); return; } setBar(bar.filter((x) => x !== id)); }
    else { if (bar.length >= 4) { toast && toast('Max 4 tabs — remove one first'); return; } setBar(bar.concat([id])); }
  };
  const moveBar = (id, dir) => {
    const i = bar.indexOf(id), j = i + dir;
    if (j < 0 || j >= bar.length) return;
    const next = bar.slice(); const t = next[i]; next[i] = next[j]; next[j] = t; setBar(next);
  };
  const toggleRad = (id) => {
    if (radial.includes(id)) { if (radial.length <= 2) { toast && toast('Keep at least 2 actions'); return; } setRadial(radial.filter((x) => x !== id)); }
    else { if (radial.length >= 8) { toast && toast('Max 8 actions'); return; } setRadial(radial.concat([id])); }
  };

  const save = () => { onSave({ bar, radial, pid: cfg.pid }); onClose(); toast && toast('Nav saved for ' + (persona.label || 'this persona')); };
  const reset = () => { setBar(window.NAV_DEFAULT_BAR.slice()); setRadial(window.NAV_DEFAULT_RADIAL.slice()); };

  const ic = (it, sz) => it.avatar ? (window.MI.user ? window.MI.user({ width: sz, height: sz }) : '◔') : it.icon({ width: sz, height: sz });

  return (
    <div className="sheet-bg" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="sheet">
        <div className="sheet-grab" />
        <div className="sheet-head">
          <button className="glass-pill" style={{ background: 'var(--bg-3)', color: 'var(--fg)', border: '1px solid var(--line)' }} onClick={reset}>Reset</button>
          <h3>Customise nav</h3>
          <button className="glass-pill" style={{ background: 'var(--accent)', color: 'var(--accent-ink)', border: 'none' }} onClick={save}>Done</button>
        </div>
        <div className="sheet-scroll">
          <div className="nc-persona">{window.MI.sync ? window.MI.sync({ width: 14, height: 14 }) : ''} Saved for your <b>{persona.label || 'Profile'}</b> persona</div>

          {/* live bar preview */}
          <div className="nc-preview">
            {(() => {
              const left = bar.slice(0, 2), right = bar.slice(2);
              const cells = [...left, '__create', ...right];
              return cells.map((id, i) => id === '__create'
                ? <span key="c" className="nc-prev-fab">{window.MI.plus({ width: 20, height: 20 })}</span>
                : <span key={id} className="nc-prev-item">{ic(POOL[id], 20)}</span>);
            })()}
          </div>

          <div className="ex-grouplabel">Bottom bar · {bar.length}/4 tabs</div>
          <div className="ex-hint" style={{ marginBottom: 12 }}>The centre + button is always there. Pick up to 4 tabs around it and order them.</div>
          {bar.map((id, i) => (
            <div className="nc-row active" key={id}>
              <span className="nc-ic">{ic(POOL[id], 18)}</span>
              <span className="nc-lb">{POOL[id].label}</span>
              <div className="nc-ord">
                <button disabled={i === 0} onClick={() => moveBar(id, -1)}>{window.MI.chevron ? window.MI.chevron({ width: 15, height: 15 }) : '▲'}</button>
                <button disabled={i === bar.length - 1} onClick={() => moveBar(id, 1)}>{window.MI.chevron ? window.MI.chevron({ width: 15, height: 15 }) : '▼'}</button>
              </div>
              <button className={'switch on'} onClick={() => toggleBar(id)} />
            </div>
          ))}
          {barPool.filter((id) => !bar.includes(id)).map((id) => (
            <div className="nc-row" key={id}>
              <span className="nc-ic">{ic(POOL[id], 18)}</span>
              <span className="nc-lb">{POOL[id].label}</span>
              <button className="switch" onClick={() => toggleBar(id)} />
            </div>
          ))}

          <div className="ex-grouplabel">Quick-create dial · {radial.length} actions</div>
          <div className="ex-hint" style={{ marginBottom: 12 }}>What fans out when you tap the centre + button.</div>
          {radPool.map((id) => (
            <div className={'nc-row' + (radial.includes(id) ? ' active' : '')} key={id}>
              <span className="nc-ic">{RPOOL[id].icon({ width: 18, height: 18 })}</span>
              <span className="nc-lb">{RPOOL[id].label}</span>
              <button className={'switch' + (radial.includes(id) ? ' on' : '')} onClick={() => toggleRad(id)} />
            </div>
          ))}
          <div style={{ height: 18 }} />
        </div>
      </div>
    </div>
  );
}
window.NavCustomizeSheet = NavCustomizeSheet;

/* global upload progress overlay — listens for 'tappt-upload' events from readMedia */
function UploadOverlay() {
  const [st, setSt] = ncUse(null);   // { pct, kind } | null
  React.useEffect(() => {
    let hideT = null;
    const on = (e) => {
      const { pct, done, kind } = e.detail || {};
      clearTimeout(hideT);
      if (done || pct >= 100) { setSt({ pct: 100, kind }); hideT = setTimeout(() => setSt(null), 500); }
      else setSt({ pct: pct || 1, kind });
    };
    window.addEventListener('tappt-upload', on);
    return () => { window.removeEventListener('tappt-upload', on); clearTimeout(hideT); };
  }, []);
  if (!st) return null;
  const r = 30, circ = 2 * Math.PI * r;
  return (
    <div className="upl-overlay">
      <div className="upl-card">
        <svg className="upl-ring" viewBox="0 0 72 72" width="72" height="72">
          <circle cx="36" cy="36" r={r} fill="none" stroke="var(--line-2)" strokeWidth="5" />
          <circle cx="36" cy="36" r={r} fill="none" stroke="var(--accent)" strokeWidth="5" strokeLinecap="round"
            strokeDasharray={circ} strokeDashoffset={circ * (1 - st.pct / 100)} transform="rotate(-90 36 36)" style={{ transition: 'stroke-dashoffset 0.25s' }} />
        </svg>
        <div className="upl-pct">{st.pct}%</div>
        <div className="upl-label">{st.pct >= 100 ? 'Done' : ('Uploading ' + (st.kind === 'video' ? 'video' : 'image') + '…')}</div>
        <div className="upl-sub">{st.pct >= 100 ? 'Saved to your profile' : 'Hang tight — larger files take a moment'}</div>
      </div>
    </div>
  );
}
window.UploadOverlay = UploadOverlay;

/* owner-only dash strip: compact NFC card upsell / order status with rotating card art */
function DashStrip({ user, toast }) {
  const MI2 = window.MI;
  const CARDS = window.CARDS || [];
  const demoOrder = user.cardOrder;
  // pull the buyer's REAL latest order from the cloud (Shopify → Supabase). Demo/paired
  // local order always wins; otherwise show the live order status.
  const [cloudOrder, setCloudOrder] = ncUse(null);
  ncEffect(() => {
    let alive = true;
    if (demoOrder) return;
    if (window.TapptDB && window.TapptDB.available() && user.email) {
      window.TapptDB.listOrders(user.email).then((rows) => {
        if (!alive || !rows || !rows.length) return;
        const o = rows.find((r) => r.status !== 'cancelled') || rows[0];
        if (!o) return;
        setCloudOrder({ card: o.productTitle, status: o.status === 'cancelled' ? 'placed' : o.status, paired: false, orderNo: o.orderNo, cancelled: o.status === 'cancelled' });
      }).catch(() => {});
    }
    return () => { alive = false; };
  }, [demoOrder, user.email]);
  const order = demoOrder || cloudOrder;
  const steps = ['placed', 'shipped', 'delivered'];
  const stIdx = order ? Math.max(0, steps.indexOf(order.status || 'placed')) : -1;
  const [ci, setCi] = ncUse(0);
  ncEffect(() => {
    if (order || !CARDS.length) return;
    const t = setInterval(() => setCi((n) => (n + 1) % CARDS.length), 2200);
    return () => clearInterval(t);
  }, [order]);

  const [pairOpen, setPairOpen] = ncUse(false);
  const [infoOpen, setInfoOpen] = ncUse(false);
  if (order) {
    const delivered = stIdx >= 2;
    return (
      <div className="dash-strip">
        <div className="ds-card ds-order">
          <div className="ds-order-body">
            <div className="ds-order-art" style={{ background: order.grad || 'linear-gradient(135deg,#2a2a30,#0e0e12)' }}>{order.img ? <img src={order.img} alt="" /> : (MI2.card ? MI2.card({ width: 20, height: 20 }) : '▭')}</div>
            <div className="ds-order-meta">
              <div className="ds-order-t">{order.card || 'NFC Card'} {order.paired ? 'paired' : 'ordered'}</div>
              <div className="ds-order-s">{order.paired ? 'Linked to your profile · tap to share' : delivered ? 'Delivered — activate it now' : stIdx === 1 ? 'On its way to you' : "We're preparing it for dispatch"}</div>
            </div>
            <span className={'ds-order-badge st-' + (order.paired ? 'delivered' : (order.status || 'placed'))}>{order.paired ? 'Active' : delivered ? 'Delivered' : (order.status === 'shipped' ? 'Shipped' : 'Processing')}</span>
          </div>
          {order.paired ? (
            <button className="ds-activate done" onClick={(e) => { e.stopPropagation(); setPairOpen(true); }}>{MI2.check ? MI2.check({ width: 17, height: 17 }) : '✓'} Card active · manage</button>
          ) : delivered ? (
            <button className="ds-activate" onClick={(e) => { e.stopPropagation(); setPairOpen(true); }}>{MI2.card ? MI2.card({ width: 18, height: 18 }) : ''} Tap to activate</button>
          ) : (
            <div className="ds-track">
              {[['placed', 'Placed', 'box'], ['shipped', 'Shipped', 'truck'], ['delivered', 'Delivered', 'pin']].map(([id, lb, ic], i) => (
                <div className={'ds-track-step' + (i <= stIdx ? ' done' : '') + (i === stIdx ? ' current' : '')} key={id}>
                  <span className="ds-track-ic">{MI2[ic] ? MI2[ic]({ width: 14, height: 14 }) : (i + 1)}</span>
                  <span className="ds-track-lb">{lb}</span>
                </div>
              ))}
            </div>
          )}
          {!order.paired && delivered && <div style={{ height: 2 }} />}
        </div>
        {pairOpen && <CardPairSheet user={user} order={order} onClose={() => setPairOpen(false)} toast={toast} />}
      </div>
    );
  }

  const card = CARDS[ci] || {};
  return (
    <div className="dash-strip">
      <div className="ds-card ds-upsell2" onClick={() => { window.location.href = 'https://tappt.io/#shop'; }} role="button">
        <div className="ds-up2-art">
          {CARDS.map((c, i) => <img key={c.id} src={c.img} alt="" className={'ds-up2-img' + (i === ci ? ' on' : '')} />)}
        </div>
        <div className="ds-up2-meta">
          <div className="ds-up2-t">Upgrade to NFC</div>
          <div className="ds-up2-s">{card.name ? card.name + ' · tap to share' : 'One tap shares your profile'} · £29.97</div>
          <span className="ds-up2-cta">Shop cards {MI2.arrow ? MI2.arrow({ width: 14, height: 14 }) : '→'}</span>
        </div>
        <button className="ds-up2-info" aria-label="How NFC cards work" onClick={(e) => { e.stopPropagation(); setInfoOpen(true); }}>{MI2.help ? MI2.help({ width: 17, height: 17 }) : 'i'}</button>
      </div>
      {infoOpen && <NFCExplainerSheet user={user} onClose={() => setInfoOpen(false)} />}
    </div>
  );
}
window.DashStrip = DashStrip;

/* which device frame to draw in the NFC explainer: match the viewer's phone */
function nfcDevice() {
  try {
    var p = window.tapptPlatform ? window.tapptPlatform() : 'web';
    if (p === 'android') return 'android';
    if (p === 'ios') return 'ios';
    var ua = navigator.userAgent || '';
    if (/android/i.test(ua)) return 'android';
    return 'ios';
  } catch (e) { return 'ios'; }
}

/* Beautiful NFC explainer — phone mockup (device-matched) showing the user's
   own live profile, an NFC card tapping it with radiating waves, then the how. */
function NFCExplainerSheet({ user, onClose }) {
  const MI2 = window.MI;
  const OwnProfile = window.OwnProfile;
  const CARDS = window.CARDS || [];
  const device = nfcDevice();
  const handle = user.handle || 'you';
  const noop = () => {};
  // prefer the card they ordered/paired, else the first catalogue card
  const heroImg = (user.cardOrder && typeof user.cardOrder.img === 'string' && user.cardOrder.img.indexOf('idb:') !== 0 && user.cardOrder.img)
    || (CARDS[0] && CARDS[0].img) || null;
  const steps = [
    ['wifi', 'Tap your card', 'Hold it to the back of any phone — top edge, like a contactless payment.'],
    ['phone', 'Their profile opens', <React.Fragment key="s2">Your live page at <b>tappt.io/{handle}</b> pops up instantly — no app, no QR.</React.Fragment>],
    ['heart', 'They connect', 'Save your contact, follow, tip or shop — all in a few seconds.'],
  ];
  return (
    <div className="sheet-bg exchange-bg nfc-bg" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="exchange-sheet nfc-sheet">
        <button className="nfc-close" aria-label="Close" onClick={onClose}>{MI2.close ? MI2.close({ width: 18, height: 18 }) : '✕'}</button>
        <div className="nfc-hero">
          <div className="nfc-stage">
            <div className={'nfc-phone nfc-phone-' + device}>
              <span className="nfc-phone-cam" />
              <div className="nfc-phone-screen">
                <div className="nfc-screen-scale">
                  {OwnProfile ? <OwnProfile user={user} pub viewer={user} toast={noop} onShare={noop} onEdit={noop} onMenu={noop} onPersona={noop} onMoments={noop} /> : null}
                </div>
              </div>
            </div>
            <div className="nfc-waves" aria-hidden="true"><span /><span /><span /></div>
            <div className="nfc-card-vis" aria-hidden="true">
              {heroImg ? <img src={heroImg} alt="" /> : <span className="nfc-card-fallback">{MI2.bolt ? MI2.bolt({ width: 18, height: 18 }) : '⚡'} tappt</span>}
            </div>
          </div>
        </div>
        <div className="nfc-body">
          <span className="nfc-kicker">{MI2.wifi ? MI2.wifi({ width: 14, height: 14 }) : '))'} NFC · Near-field tap</span>
          <h2 className="nfc-h">One tap. Your whole profile.</h2>
          <p className="nfc-sub">Every Tappt card has a tiny chip inside. Hold it near a phone and your profile opens in an instant — nothing to download, nothing to scan.</p>
          <div className="nfc-steps">
            {steps.map(([ic, t, d], i) => (
              <div className="nfc-step" key={i}>
                <span className="nfc-step-n">{MI2[ic] ? MI2[ic]({ width: 17, height: 17 }) : (i + 1)}</span>
                <div className="nfc-step-tx"><div className="nfc-step-t">{t}</div><div className="nfc-step-d">{d}</div></div>
              </div>
            ))}
          </div>
          <button className="nfc-cta" onClick={() => { window.location.href = 'https://tappt.io/#shop'; }}>Shop cards · £29.97 {MI2.arrow ? MI2.arrow({ width: 16, height: 16 }) : '→'}</button>
          <p className="nfc-foot">Works with iPhone XS &amp; later and all modern Android phones.</p>
        </div>
      </div>
    </div>
  );
}
window.NFCExplainerSheet = NFCExplainerSheet;

/* card pairing / activation flow (Liorra-style) */
function CardPairSheet({ user, order, onClose, toast }) {
  const MI2 = window.MI;
  const paired = !!(order && order.paired);
  const [done, setDone] = ncUse(paired);
  const [writing, setWriting] = ncUse(false);
  const personas = (window.getPersonas ? window.getPersonas(user) : (user.personas || []));
  const [persona, setPersona] = ncUse((order && order.persona) || (personas[0] && personas[0].id) || 'default');
  const handle = user.handle || 'you';
  const cardImg = (order && typeof order.img === 'string' && order.img.indexOf('idb:') !== 0) ? order.img : null;
  const write = () => {
    setWriting(true);
    setTimeout(() => {
      const cur = (JSON.parse(localStorage.getItem('tappt_app_v1')) || {}).user || user;
      const pairedAt = Date.now();
      window.Store.saveUser(Object.assign({}, cur, { cardOrder: Object.assign({}, cur.cardOrder, { paired: true, pairedAt: pairedAt, persona: persona }) }));
      if (window.Store.saveCard) {
        const card = { id: (window.newId ? window.newId() : 'card' + pairedAt), cardType: cur.activeCard || (cur.cardOrder && cur.cardOrder.cardId) || null, cardImg: cardImg, status: 'paired', paired: true, persona: persona, pairedAt: pairedAt };
        window.Store.saveCard(card);
      }
      setWriting(false); setDone(true);
      toast && toast('Card paired');
    }, 1600);
  };
  return (
    <div className="sheet-bg exchange-bg" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="exchange-sheet pair-sheet">
        <div className={'pair-card-vis' + (done ? ' paired' : '')}>
          {cardImg ? <img className="pair-card-img" src={cardImg} alt="" /> : <React.Fragment><span className="pair-nfc">{MI2.wifi ? MI2.wifi({ width: 20, height: 20 }) : '))'}</span><span className="pair-logo">{MI2.bolt ? MI2.bolt({ width: 15, height: 15 }) : '⚡'} tappt</span></React.Fragment>}
          {done && <span className="pair-badge">{MI2.check ? MI2.check({ width: 12, height: 12 }) : '✓'} Card paired</span>}
        </div>
        <h2 className="pair-h">{done ? 'Your card is set up' : 'Set up your card'}</h2>
        <p className="pair-sub">{done ? 'This card points to your profile. Tap it on any phone to share.' : 'Your card links directly to your profile when someone taps it.'}</p>
        <div className="pair-url">tappt.io/ <b>{handle}</b></div>
        {personas.length > 1 && (
          <div className="pair-persona">
            <div className="pair-persona-l">Link this card to</div>
            <div className="pair-persona-row">
              {personas.map((p) => <button key={p.id} className={'pair-persona-chip' + (persona === p.id ? ' on' : '')} onClick={() => setPersona(p.id)} disabled={done}>{p.label || p.name || 'Profile'}</button>)}
            </div>
          </div>
        )}
        {done ? (
          <div className="pair-actions">
            <button className="pair-secondary" onClick={() => { setDone(false); }}>{MI2.plus ? MI2.plus({ width: 16, height: 16 }) : '+'} Pair another card</button>
            <button className="pair-primary" onClick={onClose}>Done</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="pair-steps">
              {[['phone', 'Hold your NFC card ready'], ['wifi', "Tap 'Write to card' below"], ['card', 'Hold card against your phone'], ['lock', "That's it — your card is set up!"]].map(([ic, t], i) => (
                <div className="pair-step" key={i}><span className="pair-step-ic">{MI2[ic] ? MI2[ic]({ width: 18, height: 18 }) : (i + 1)}</span><span>{t}</span></div>
              ))}
            </div>
            <button className={'pair-write' + (writing ? ' writing' : '')} onClick={write} disabled={writing}>{writing ? 'Hold steady…' : <React.Fragment>{MI2.card ? MI2.card({ width: 18, height: 18 }) : ''} Write to card</React.Fragment>}</button>
            <button className="ex-notnow" onClick={onClose}>Later</button>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}
window.CardPairSheet = CardPairSheet;

/* ---- My Cards manager: list cards, re-aim persona per card, add a card ---- */
function CardsScreen({ user, setUser, toast, onClose }) {
  const MI2 = window.MI;
  const personas = (window.getPersonas ? window.getPersonas(user) : (user.personas || [{ id: 'main', label: 'Main' }]));
  const [cards, setCards] = ncUse(user.cards || []);
  const [adding, setAdding] = ncUse(false);
  const [codeIn, setCodeIn] = ncUse('');
  const [busy, setBusy] = ncUse(false);
  const [openMenu, setOpenMenu] = ncUse(null);

  const persist = (next) => {
    setCards(next);
    const nu = Object.assign({}, user, { cards: next });
    setUser(nu); try { window.Store.saveUser(nu); } catch (e) {}
  };
  const setPersona = (id, pid) => {
    persist(cards.map((c) => c.id === id ? Object.assign({}, c, { persona: pid }) : c));
    setOpenMenu(null);
    if (window.TapptDB && window.TapptDB.available() && window.TapptDB.collections) { try { window.TapptDB.collections.upsert('cards', cards.find((c) => c.id === id), user.id); } catch (e) {} }
    toast && toast('Card re-aimed');
  };
  const rename = (id, label) => persist(cards.map((c) => c.id === id ? Object.assign({}, c, { label: label }) : c));
  const removeCard = (id) => { persist(cards.filter((c) => c.id !== id)); setOpenMenu(null); toast && toast('Card removed'); };
  const copyLink = (c) => { var url = 'tappt.io/c/' + (c.code || ''); try { navigator.clipboard.writeText('https://' + url); } catch (e) {} toast && toast('Card link copied'); };

  const addCard = async () => {
    var code = codeIn.trim().replace(/^.*\/c\//, '').replace(/[^A-Za-z0-9]/g, '');
    if (!code) { toast && toast('Enter your card code'); return; }
    setBusy(true);
    var pid = personas[0] && personas[0].id;
    try {
      if (window.TapptDB && window.TapptDB.available()) { await window.TapptDB.claimCard(code, pid); }
      var nc = { id: window.newId ? window.newId() : ('c' + Date.now()), code: code, persona: pid, status: 'delivered', paired: true, claimed: true, label: 'Tappt Card' };
      persist([nc].concat(cards));
      setAdding(false); setCodeIn(''); toast && toast('Card added');
    } catch (e) { toast && toast((e && e.message === 'already_claimed') ? 'That card is claimed by another account' : 'Could not add card'); }
    setBusy(false);
  };

  const pLabel = (pid) => { var p = personas.find((x) => x.id === pid); return p ? (p.label || p.name || 'Profile') : (personas[0] ? (personas[0].label || 'Profile') : 'Profile'); };

  return (
    <div className="sheet-bg" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="sheet">
        <div className="sheet-grab" />
        <div className="sheet-head">
          <span style={{ width: 56 }} />
          <h3>My Cards</h3>
          <button className="glass-pill" style={{ background: 'var(--accent)', color: 'var(--accent-ink)', border: 'none' }} onClick={onClose}>Done</button>
        </div>
        <div className="sheet-scroll">
          <div className="ex-hint" style={{ marginBottom: 16 }}>Point each card at any persona — even one that isn't live. Your <b style={{ color: 'var(--fg)' }}>bio link</b> always shows your LIVE persona; each <b style={{ color: 'var(--fg)' }}>card</b> opens whichever persona you aim it at. Re-aim any time — the chip never needs rewriting.</div>

          {cards.length === 0 && !adding && (
            <React.Fragment>
              <button className="cards-upsell" onClick={() => { window.location.href = 'https://tappt.io/#shop'; }}>
                <span className="cards-upsell-art">{MI2.card ? MI2.card({ width: 26, height: 26 }) : ''}</span>
                <span className="cards-upsell-meta">
                  <span className="cards-upsell-t">Get your Tappt card</span>
                  <span className="cards-upsell-s">One tap shares your profile in real life. Pick your design — from £29.97.</span>
                  <span className="cards-upsell-cta">Shop cards {MI2.arrowRight ? MI2.arrowRight({ width: 14, height: 14 }) : '→'}</span>
                </span>
              </button>
              <div className="cards-have">
                Already got one? <button onClick={() => setAdding(true)}>Enter its code</button>
              </div>
            </React.Fragment>
          )}

          {cards.map((c) => {
            var img = (typeof c.img === 'string' && c.img.indexOf('idb:') !== 0) ? c.img : (typeof c.cardImg === 'string' ? c.cardImg : null);
            return (
              <div className="mycard-row" key={c.id}>
                <span className="mycard-art" style={{ background: c.grad || 'linear-gradient(135deg,#2a2a30,#0e0e12)' }}>{img ? <img src={img} alt="" /> : (MI2.card ? MI2.card({ width: 18, height: 18 }) : '')}</span>
                <div className="mycard-meta">
                  <div className="mycard-name">{c.label || c.cardType || 'Tappt Card'}</div>
                  <div className="mycard-code">tappt.io/c/{c.code || '—'}</div>
                </div>
                <div className="mycard-persona-wrap">
                  <span className="mycard-opens">Opens</span>
                  <button className="mycard-persona" onClick={() => setOpenMenu(openMenu === c.id ? null : c.id)}>{pLabel(c.persona)} {MI2.chevron ? MI2.chevron({ width: 13, height: 13 }) : '▾'}</button>
                  {openMenu === c.id && (
                    <React.Fragment>
                      <div className="mycard-veil" onClick={() => setOpenMenu(null)} />
                      <div className="mycard-menu">
                        {personas.map((p) => <button key={p.id} className={'mycard-opt' + (c.persona === p.id ? ' on' : '')} onClick={() => setPersona(c.id, p.id)}>{p.label || p.name || 'Profile'}</button>)}
                        <div className="mycard-sep" />
                        <button className="mycard-opt" onClick={() => copyLink(c)}>Copy card link</button>
                        <button className="mycard-opt del" onClick={() => removeCard(c.id)}>Remove card</button>
                      </div>
                    </React.Fragment>
                  )}
                </div>
              </div>
            );
          })}

          {adding ? (
            <div className="mycard-add">
              <input className="input" placeholder="Card code (or tappt.io/c/…)" value={codeIn} onChange={(e) => setCodeIn(e.target.value)} autoFocus />
              <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                <button className="btn btn-ghost btn-sm" style={{ flex: 1 }} onClick={() => { setAdding(false); setCodeIn(''); }}>Cancel</button>
                <button className="btn btn-primary btn-sm" style={{ flex: 1 }} disabled={busy} onClick={addCard}>{busy ? 'Adding…' : 'Add card'}</button>
              </div>
            </div>
          ) : (cards.length > 0 && (
            <button className="mycard-addbtn" onClick={() => setAdding(true)}>{MI2.plus ? MI2.plus({ width: 16, height: 16 }) : '+'} Add a card</button>
          ))}
          <div style={{ height: 16 }} />
        </div>
      </div>
    </div>
  );
}
window.CardsScreen = CardsScreen;
