// ─────────────────────────────────────────────────────────────────
// SIKKA ROYALE — Home / Wallet / Settings / Bottom tab nav
// ─────────────────────────────────────────────────────────────────

// ── WhatsApp concierge prefill ─────────────────────────────────────
// Builds a wa.me deep-link carrying a real, pre-written message that
// names the visitor and their linked cards — so the concierge chat
// opens warm and actionable, never as a blank thread. Rebuilt on every
// click so it reflects the current journey state. Mirrors the message
// shape used on the /vision surface.
const SIKKA_WA_NUMBER = '12019794438';
function sikkaWhatsappHref({ name = '', linkedIds = [], pay = null, ask = null } = {}) {
  const lines = [];
  const first = (name || '').trim().split(' ')[0];
  lines.push('Hi Sikka' + (first ? ' — ' + first + ' here.' : '.'));

  const catalogue = (typeof ROYAL_CATALOGUE !== 'undefined') ? ROYAL_CATALOGUE : [];
  const cards = (linkedIds || [])
    .map((id) => catalogue.find((c) => c.id === id))
    .filter(Boolean);
  if (cards.length > 0) {
    lines.push('');
    lines.push('My linked cards:');
    for (const c of cards) {
      lines.push('• ' + c.name + (c.last4 ? ' ····' + c.last4 : ''));
    }
  }

  lines.push('');
  if (ask) {
    lines.push(ask);
  } else if (pay && pay.merchant && Number(pay.amount) > 0) {
    lines.push('About to spend AED ' + Number(pay.amount) + ' at ' + pay.merchant + ' — which card should I use?');
  } else if (cards.length > 0) {
    lines.push('Which card should I use for my next spend?');
  } else {
    lines.push('Just joined — which cards should I link first for UAE groceries, dining and bills?');
  }

  return 'https://wa.me/' + SIKKA_WA_NUMBER + '?text=' + encodeURIComponent(lines.join('\n'));
}
function openSikkaWhatsapp(opts) {
  try { window.open(sikkaWhatsappHref(opts), '_blank', 'noopener'); } catch (e) {}
}

// ── Brand image-slot — wraps <image-slot> with the velvet/gold chrome
// so a user can drop in real WhatsApp / merchant logos. Until then it
// shows a neutral serif monogram (initial prop) — typography only, never
// mimicking a real brand mark.
function BrandSlot({ id, placeholder = 'Drop logo', size = 44, radius = 10,
  bg = R.ink3, border = R.hair2, initial, domain }) {
  // Real brand logo when we know the domain; falls back to monogram on load failure.
  if (domain) {
    return <BrandTile size={size} radius={radius} domain={domain} initial={initial} bg={bg} tx={R.gold} />;
  }
  const fontSize = Math.max(11, Math.round(size * 0.42));
  return (
    <div style={{
      width: size, height: size, flexShrink: 0, position: 'relative',
      borderRadius: radius, overflow: 'hidden',
      background: bg, border: `0.5px solid ${border}`,
      boxShadow: 'inset 0 0 0 0.5px rgba(255,255,255,0.04)',
    }}>
      {/* Neutral monogram — serif letter on velvet, no brand mimicry */}
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: R.gold, opacity: initial ? 1 : 0.55, pointerEvents: 'none',
      }}>
        {initial ? (
          <span style={{
            fontFamily: FR.serif, fontSize, fontStyle: 'italic', fontWeight: 500,
            letterSpacing: -0.5, color: R.gold,
            textShadow: '0 1px 0 rgba(0,0,0,0.35)',
          }}>{initial}</span>
        ) : (
          <svg width={size * 0.42} height={size * 0.42} viewBox="0 0 24 24" fill="none">
            <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="1.4"
              strokeLinecap="round" />
            <circle cx="12" cy="12" r="9" stroke="currentColor"
              strokeWidth="0.6" opacity="0.5" />
          </svg>
        )}
      </div>
      {React.createElement('image-slot', {
        id, placeholder, fit: 'cover', shape: 'rect',
        style: { position: 'absolute', inset: 0, width: '100%', height: '100%',
          display: 'block' },
      })}
    </div>
  );
}

// ── The Royal Wallet card — velvet panel, gold filigree, seal ──────
function RoyalWalletCard({ name = 'Khalid Al Mansoori', last4 = '2026',
  tier = 'NOIR', memberSince = '2026' }) {
  return (
    <div style={{
      position: 'relative', width: '100%', aspectRatio: '1.62',
      borderRadius: 20, overflow: 'hidden',
      background: `
        radial-gradient(ellipse 60% 50% at 18% 0%, rgba(74,155,122,0.18), transparent 60%),
        radial-gradient(ellipse 70% 60% at 100% 100%, rgba(14,28,24,0.45), transparent 60%),
        linear-gradient(135deg, #0e1c18 0%, #0a0e10 50%, #10221c 100%)
      `,
      border: `0.5px solid ${R.hair3}`,
      boxShadow: '0 30px 60px rgba(0,0,0,0.65), inset 0 0 0 0.5px rgba(74,155,122,0.10)',
      color: R.pearl,
    }}>
      {/* Guilloché engraving */}
      <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice"
        style={{ position: 'absolute', inset: 0, opacity: 0.16, pointerEvents: 'none' }}>
        <g fill="none" stroke={R.gold} strokeWidth="0.3">
          {Array.from({ length: 22 }).map((_, i) => (
            <circle key={i} cx="80" cy="125" r={20 + i * 11} />
          ))}
          {Array.from({ length: 22 }).map((_, i) => (
            <circle key={'b'+i} cx="320" cy="125" r={20 + i * 11} />
          ))}
        </g>
      </svg>

      <FiligreeCorners color={R.gold} inset={10} length={20} opacity={0.5} />

      <div style={{ position: 'relative', height: '100%', padding: '18px 22px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>

        {/* Top: tier + NFC */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Eyebrow color={R.gold} ls={3.2} size={9.5}>SIKKA · NOIR</Eyebrow>
            <div style={{
              fontFamily: FR.display, fontSize: 18, color: R.pearl,
              letterSpacing: 4, marginTop: 8, fontWeight: 600, textTransform: 'uppercase',
            }}>{name.split(' ')[0]}</div>
            <Eyebrow color={R.pearl3} ls={1.8} size={9} style={{ marginTop: 4 }}>
              MEMBER SINCE {memberSince}
            </Eyebrow>
          </div>
          {/* Tiny seal in corner */}
          <RoyalSeal size={56} motion={true} />
        </div>

        {/* Bottom: number + name + chip */}
        <div>
          {/* chip + nfc */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <GoldChip width={38} height={28} radius={5} />
            <span style={{ color: R.pearl3, fontFamily: FR.mono, fontSize: 14 }}>))</span>
          </div>
          <div style={{
            fontFamily: FR.mono, fontSize: 16, color: R.pearl2,
            letterSpacing: 1.8, marginBottom: 12,
          }}>···· ····  ····  <span style={{ color: R.pearl }}>{last4}</span></div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          }}>
            <Eyebrow color={R.pearl2} ls={2.4} size={9.5}>{name.toUpperCase()}</Eyebrow>
            <Eyebrow color={R.pearl2} ls={2.4} size={9.5}>12 / 30</Eyebrow>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Stat tile — small card, gold accent value ──────────────────────
function StatTile({ label, sub, value }) {
  return (
    <div style={{
      padding: '12px 14px 14px', background: R.ink2,
      border: `0.5px solid ${R.hair}`, borderRadius: 12, position: 'relative',
    }}>
      <Eyebrow size={9} ls={2}>{label}</Eyebrow>
      <div style={{ marginTop: 8, display: 'flex', alignItems: 'baseline', gap: 2 }}>
        {value}
      </div>
      <Eyebrow size={9} ls={1.6} color={R.pearl4} style={{ marginTop: 6, textTransform: 'none' }}>
        {sub}
      </Eyebrow>
    </div>
  );
}

function Num({ children, size = 26, color = R.pearl, style }) {
  return (
    <span style={{
      fontFamily: FR.mono, fontSize: size * 0.55, color,
      letterSpacing: 1, ...style,
    }}>{children}</span>
  );
}

// ── Quick action tile ──────────────────────────────────────────────
function QuickTile({ label, sub, icon, onClick }) {
  return (
    <button onClick={onClick} style={{
      position: 'relative', width: '100%', textAlign: 'left',
      padding: '12px 12px', background: R.ink2,
      border: `0.5px solid ${R.hair}`, borderRadius: 14, cursor: 'pointer',
      color: R.pearl, display: 'flex', flexDirection: 'column', gap: 10, minHeight: 96,
      overflow: 'hidden', minWidth: 0,
    }}>
      <div style={{
        width: 34, height: 34, borderRadius: 9, background: R.goldDim,
        border: `0.5px solid ${R.gold}33`, color: R.gold,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>{icon}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontFamily: FR.serif, fontSize: 16, color: R.pearl,
          letterSpacing: -0.2, fontWeight: 500, fontStyle: 'italic',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{label}</div>
        <Eyebrow size={8.5} ls={1.4} color={R.pearl3} style={{
          marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block',
        }}>{sub}</Eyebrow>
      </div>
    </button>
  );
}

function GoalCard({ icon, label, pct, sub }) {
  return (
    <div style={{
      padding: '14px 16px', background: R.ink2,
      border: `0.5px solid ${R.hair}`, borderRadius: 12, position: 'relative',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 18, lineHeight: 1, color: R.gold }}>{icon}</span>
          <span style={{
            fontFamily: FR.serif, fontSize: 16, color: R.pearl,
            letterSpacing: -0.2, fontWeight: 500,
          }}>{label}</span>
        </div>
        <Eyebrow size={11} color={R.gold}>{pct}%</Eyebrow>
      </div>
      <ProgressBar pct={pct} height={3} style={{ marginTop: 12 }} />
      <Eyebrow size={9.5} ls={1.6} color={R.pearl4} style={{ marginTop: 8, textTransform: 'none' }}>
        {sub}
      </Eyebrow>
    </div>
  );
}

// ── Home screen ────────────────────────────────────────────────────
function HomeScreen({ name = '', linkedCount = 2, linked = [], onPay, onSettings, onMarketplace,
  onPayBills, onWallet }) {
  const hour = new Date().getHours();
  const enSalute = hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening';
  // Dark-psychology salutes — loss aversion + social proof, no "coin" metaphor.
  const subSalute = hour < 12 ? 'Today, the careless pay for the careful'
    : hour < 17 ? 'While they spend, you collect'
    : "What you didn't earn today, someone else did";

  return (
    <div className="r-screen" style={{
      minHeight: '100dvh', background: R.ink, color: R.pearl,
      paddingBottom: 96,
    }}>
      {/* Mast */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '18px 22px 0',
        animation: 'r-rise-soft 600ms both',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <CoinMark size={32} />
          <span style={{
            fontFamily: FR.display, fontSize: 18, color: R.pearl,
            letterSpacing: 5, fontWeight: 600,
          }}>SIKKA</span>
        </div>
        <button onClick={onSettings} aria-label="Settings" style={{
          width: 42, height: 42, borderRadius: '50%', cursor: 'pointer',
          background: R.goldDim, border: `0.5px solid ${R.gold}66`,
          color: R.gold, fontFamily: FR.display, fontSize: 12, letterSpacing: 1.4,
          fontWeight: 600,
        }}>{name[0]}S</button>
      </div>

      {/* Salute */}
      <div style={{ padding: '24px 22px 0', animation: 'r-rise 600ms 80ms both' }}>
        <Eyebrow color={R.gold} ls={3.2} size={10}>
          {enSalute.toUpperCase()} · {(name || 'Khalid Al Mansoori').toUpperCase()}
        </Eyebrow>
        <Headline lead={subSalute.split(' ').slice(0, -1).join(' ')}
          tail={subSalute.split(' ').slice(-1)[0]} tailPunct="."
          size={32} style={{ marginTop: 14 }} />
      </div>

      {/* Wallet card */}
      <div style={{ padding: '20px 22px 0', animation: 'r-rise 700ms 160ms both' }}>
        <button onClick={onWallet} style={{
          all: 'unset', display: 'block', width: '100%', cursor: 'pointer',
        }}>
          <RoyalWalletCard name={name || 'Khalid Al Mansoori'} />
        </button>
      </div>

      {/* Apple Wallet */}
      <div style={{ padding: '14px 22px 0', animation: 'r-rise-soft 600ms 240ms both' }}>
        <button style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
          gap: 12, padding: '14px 22px', cursor: 'pointer',
          background: R.ink2, color: R.pearl,
          border: `0.5px solid ${R.hair3}`, borderRadius: 12,
          fontFamily: FR.serif, fontSize: 15, fontStyle: 'italic',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path d="M17.5 12.5c0-2 1.5-3 2.5-3.5-1.3-2-3.3-2.3-4-2.3-1.7-.2-3.3 1-4.2 1-.8 0-2.2-1-3.6-1-1.9 0-3.6 1.1-4.5 2.8-1.9 3.3-.5 8.2 1.4 10.9.9 1.3 2 2.8 3.4 2.7 1.3 0 1.9-.9 3.6-.9 1.6 0 2.2.9 3.6.9 1.5 0 2.5-1.3 3.4-2.6 1.1-1.5 1.5-3 1.5-3-.1 0-2.9-1.1-2.9-4.3M14.5 4.5c.7-.9 1.2-2.1 1.1-3.3-1 0-2.3.7-3 1.6-.7.8-1.3 2-1.1 3.2 1.2 0 2.4-.6 3-1.5"/>
          </svg>
          <span>Add to Apple Wallet</span>
          <VBadge>v1.2</VBadge>
        </button>
      </div>

      {/* Stats */}
      <div style={{
        padding: '14px 22px 0',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10,
        animation: 'r-rise-soft 600ms 320ms both',
      }}>
        <StatTile label="EARNED" sub="this session"
          value={<><Num color={R.pearl}>AED&nbsp;</Num><CountUp to={25}
            style={{ fontFamily: FR.serif, fontSize: 26, color: R.gold, fontWeight: 500 }} /></>} />
        <StatTile label="SAVED"  sub="vs next best"
          value={<><Num color={R.pearl}>AED&nbsp;</Num><CountUp to={6}
            style={{ fontFamily: FR.serif, fontSize: 26, color: R.gold, fontWeight: 500 }} /></>} />
        <StatTile label="CARDS"  sub="linked"
          value={<CountUp to={linkedCount}
            style={{ fontFamily: FR.serif, fontSize: 26, color: R.pearl, fontWeight: 500 }} />} />
      </div>

      {/* Pay button */}
      <div style={{ padding: '22px 22px 0', animation: 'r-rise 700ms 400ms both' }}>
        <GoldButton onClick={onPay}>Pay with Sikka</GoldButton>
      </div>

      {/* WhatsApp banner */}
      <div style={{ padding: '14px 22px 0', animation: 'r-rise-soft 600ms 480ms both' }}>
        <button onClick={() => openSikkaWhatsapp({ name, linkedIds: linked })} style={{
          width: '100%', textAlign: 'left',
          padding: '14px 16px', background: R.ink2,
          border: `0.5px solid ${R.hair}`, borderRadius: 14, cursor: 'pointer',
          color: R.pearl, display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <BrandSlot id="logo-whatsapp" placeholder="Drop WhatsApp logo"
            size={40} radius={10} bg="#0c1a13" border="#1f4a35" initial="W" domain="whatsapp.com" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: FR.serif, fontSize: 17, color: R.pearl,
              letterSpacing: -0.2, fontWeight: 500, fontStyle: 'italic',
            }}>Connect WhatsApp</div>
            <Eyebrow color={R.pearl3} style={{ marginTop: 3 }}>
              CARD RECOMMENDATIONS, BEFORE YOU PAY
            </Eyebrow>
          </div>
          <span style={{ color: R.gold, fontSize: 16 }}>›</span>
        </button>
      </div>

      {/* Quick actions — rule of 3: Bills · Marketplace · Concierge */}
      <div style={{
        padding: '28px 22px 0', display: 'grid',
        gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 10,
        animation: 'r-rise-soft 600ms 560ms both',
      }}>
        <Eyebrow style={{ gridColumn: '1 / -1', marginBottom: 4 }} color={R.pearl4}>
          QUICK ACTIONS · إجراءات سريعة
        </Eyebrow>
        <QuickTile
          label="Bills"
          sub="DEWA · CC"
          icon={<ReceiptIcon />}
          onClick={onPayBills}
        />
        <QuickTile
          label="Souq"
          sub="OFFERS · CONVERT"
          icon={<SparkleIcon />}
          onClick={onMarketplace}
        />
        <QuickTile
          label="Concierge"
          sub="ASK SIKKA · WHATSAPP"
          icon={<WhatsAppGlyph />}
          onClick={() => openSikkaWhatsapp({ name, linkedIds: linked })}
        />
      </div>

      {/* Ornament divider */}
      <div style={{ padding: '28px 22px 0' }}>
        <StarDivider dim={0.4} />
      </div>

      {/* Activity */}
      <div style={{ padding: '22px 22px 0' }}>
        <Eyebrow color={R.pearl4}>RECENT · أحدث المعاملات</Eyebrow>
        <div style={{ marginTop: 12, background: R.ink2,
          border: `0.5px solid ${R.hair}`, borderRadius: 14, overflow: 'hidden' }}>
          {[
            { merch: 'Talabat',  slot: 'logo-talabat',   initial: 'T', bank: 'adcb', when: 'YESTERDAY',  last4: '6242', amt: '85.00',  earn: '4.25', bg: '#1a0e0a', border: '#3a2018' },
            { merch: 'ADNOC',    slot: 'logo-adnoc',     initial: 'A', bank: 'fab',  when: '2 DAYS AGO', last4: '2891', amt: '200.00', earn: '8.00', bg: '#0a1422', border: '#1a2a40' },
            { merch: 'Carrefour',slot: 'logo-carrefour', initial: 'C', bank: 'adcb', when: '3 DAYS AGO', last4: '6242', amt: '320.00', earn: '12.80', bg: '#0a1428', border: '#1a2a48' },
          ].map((t, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '44px 1fr auto',
              gap: 12, padding: '14px 16px',
              borderBottom: i < 2 ? `0.5px solid ${R.hair}` : 'none',
              animation: `r-rise-soft 500ms ${640 + i*80}ms both`,
            }}>
              <BrandSlot id={t.slot} placeholder={`Drop ${t.merch} logo`}
                size={44} radius={10} bg={t.bg} border={t.border} initial={t.initial}
                domain={BRAND_DOMAIN[t.merch]} />
              <div style={{ minWidth: 0 }}>
                <div style={{
                  fontFamily: FR.serif, fontSize: 17, color: R.pearl,
                  letterSpacing: -0.2, fontWeight: 500, fontStyle: 'italic',
                }}>{t.merch}</div>
                <Eyebrow size={9} ls={1.6} color={R.pearl3} style={{ marginTop: 3 }}>
                  {t.when} · {t.bank.toUpperCase()} ····{t.last4}
                </Eyebrow>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{
                  fontFamily: FR.mono, fontSize: 15, color: R.pearl, letterSpacing: 0.5,
                }}>AED {t.amt}</div>
                <div style={{
                  fontFamily: FR.mono, fontSize: 13, color: R.gold,
                  letterSpacing: 0.5, marginTop: 2,
                }}>+AED {t.earn}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Goals */}
      <div style={{ padding: '28px 22px 0' }}>
        <Eyebrow color={R.pearl4}>YOUR PURSUITS · أهدافك</Eyebrow>
        <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <GoalCard icon="✦" label="Earn AED 500 this month"   pct={40}
            sub="AED 200 / 500" />
          <GoalCard icon="✦" label="Unlock ENBD travel voucher" pct={62}
            sub="AED 6,200 to go" />
          <GoalCard icon="✦" label="Hit FAB cashback cap"        pct={85}
            sub="Almost maxed — keep using ADCB" />
        </div>
      </div>

      {/* Footer */}
      <div style={{
        padding: '40px 22px 12px', textAlign: 'center',
        animation: 'r-fade 600ms 900ms both',
      }}>
        <Sub style={{ color: R.pearl3, fontSize: 14, fontStyle: 'italic' }}>
          The advantage few will see.
        </Sub>
        <Sub style={{
          marginTop: 6, color: R.pearl4, fontSize: 13,
          fontFamily: FR.arabD, direction: 'rtl',
        }}>
          ميزةٌ لا يراها الكثيرون.
        </Sub>
      </div>
    </div>
  );
}

function ReceiptIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path d="M6 3v18l2-1 2 1 2-1 2 1 2-1 2 1V3" stroke="currentColor" strokeWidth="1.6"
        strokeLinejoin="round" strokeLinecap="round" />
      <path d="M9 8h6M9 12h6M9 16h3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}
function SparkleIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"
        stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

// Speech-bubble glyph for the Concierge quick-tile. Neutral — not the
// WhatsApp green logo (spec: never draw the real brand mark).
function WhatsAppGlyph() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path d="M4 18l1-3.2A7.4 7.4 0 1 1 8 19l-4 -1z"
        stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
    </svg>
  );
}

// ── Bottom tab nav — appears on top-level screens ─────────────────
function BottomTabNav({ current, onChange }) {
  const tabs = [
    { id: 'home',        label: 'Home',     icon: <HomeIcon /> },
    { id: 'pay-merchant',label: 'Pay',      icon: <PayIcon /> },
    { id: 'marketplace', label: 'Souq',     icon: <SparkleIcon /> },
    { id: 'pay-bills',   label: 'Bills',    icon: <ReceiptIcon /> },
    { id: 'settings',    label: 'You',      icon: <UserIcon /> },
  ];
  return (
    <div style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 50,
      // Desktop preview: phone frame is centered max-width 420px; clamp nav
      // width and re-center so it doesn't span the whole desktop viewport.
      maxWidth: 420, margin: '0 auto',
      padding: '10px 14px max(env(safe-area-inset-bottom), 12px)',
      background: 'linear-gradient(to top, rgba(13,9,19,0.96), rgba(13,9,19,0.85) 70%, transparent)',
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
    }}>
      <div style={{
        display: 'grid', gridTemplateColumns: `repeat(${tabs.length}, 1fr)`,
        background: R.ink2, border: `0.5px solid ${R.hair2}`,
        borderRadius: 22, padding: 6, position: 'relative',
      }}>
        {tabs.map(t => {
          const on = current === t.id;
          return (
            <button key={t.id} onClick={() => onChange(t.id)}
              style={{
                all: 'unset', cursor: 'pointer', textAlign: 'center',
                padding: '10px 6px', borderRadius: 16, transition: 'all 200ms',
                background: on ? R.goldDim : 'transparent',
                border: on ? `0.5px solid ${R.gold}55` : '0.5px solid transparent',
              }}>
              <div style={{
                color: on ? R.gold : R.pearl4,
                display: 'flex', justifyContent: 'center', marginBottom: 2,
              }}>{t.icon}</div>
              <div style={{
                fontFamily: FR.mono, fontSize: 9, letterSpacing: 1.6,
                color: on ? R.gold : R.pearl4, textTransform: 'uppercase',
              }}>{t.label}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function HomeIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path d="M4 11l8-7 8 7v9a2 2 0 01-2 2h-3v-6h-6v6H6a2 2 0 01-2-2v-9z"
        stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}
function PayIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <rect x="3" y="6" width="18" height="13" rx="2" stroke="currentColor" strokeWidth="1.6" />
      <path d="M3 10h18" stroke="currentColor" strokeWidth="1.6" />
      <path d="M7 15h3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}
function UserIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="8" r="4" stroke="currentColor" strokeWidth="1.6" />
      <path d="M4 21c0-4 4-7 8-7s8 3 8 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

// ── Settings screen ────────────────────────────────────────────────
function SettingsScreen({ name = 'Praneet', mobile = '+971 50 123 4567',
  joined = 'May 2026', linkedCount = 2, linked = [], onBack, onLogout, onBrandKit, onLinkedCards }) {
  const [toggles, setToggles] = React.useState({
    waReminders: true, daily: true, renewal: true, caps: true, milestones: false,
  });
  const flip = (k) => setToggles(t => ({ ...t, [k]: !t[k] }));

  return (
    <div className="r-screen" style={{
      minHeight: '100dvh', background: R.ink, color: R.pearl,
      paddingBottom: 120, position: 'relative',
    }}>
      <MashrabiyaBG opacity={0.03} />
      <TopBar onBack={onBack} center="SETTINGS · إعدادات" />

      {/* Hero seal + name */}
      <div style={{ padding: '12px 22px 0', textAlign: 'center', animation: 'r-rise 600ms both' }}>
        <div style={{ display: 'inline-block', marginTop: 6 }}>
          <RoyalSeal size={86} motion={true} />
        </div>
        <Headline lead={name} tail="·" tailPunct="" accent={R.gold} size={36} style={{ marginTop: 14 }} />
        <Eyebrow color={R.pearl3} style={{ marginTop: 8 }}>
          MEMBER SINCE {joined.toUpperCase()} · NOIR TIER
        </Eyebrow>
        <Sub style={{
          fontFamily: FR.mono, fontSize: 12, color: R.pearl3,
          marginTop: 10, letterSpacing: 0.5,
        }}>{mobile}</Sub>
      </div>

      {/* Notifications */}
      <div style={{ padding: '28px 22px 0' }}>
        <Eyebrow color={R.pearl4}>NOTIFICATIONS · إشعارات</Eyebrow>
        <div style={{
          marginTop: 12, background: R.ink2,
          border: `0.5px solid ${R.hair}`, borderRadius: 16, overflow: 'hidden',
        }}>
          <ToggleRow label="WhatsApp reminders before recurring payments"
            sub='"DEWA bill due tomorrow — use ADCB"'
            on={toggles.waReminders} onToggle={() => flip('waReminders')} />
          <ToggleRow label="Daily reward summary"
            sub="RECAP OF YESTERDAY'S EARNINGS"
            on={toggles.daily} onToggle={() => flip('daily')} />
          <ToggleRow label="Card renewal alerts"
            sub="30 DAYS BEFORE EXPIRY"
            on={toggles.renewal} onToggle={() => flip('renewal')} />
          <ToggleRow label="Cap warnings"
            sub='"YOU&apos;RE 80% TO YOUR MONTHLY CAP"'
            on={toggles.caps} onToggle={() => flip('caps')} />
          <ToggleRow label="Goal milestones"
            sub="25 / 50 / 75 / 100% PROGRESS"
            on={toggles.milestones} onToggle={() => flip('milestones')} last />
        </div>
      </div>

      {/* Account */}
      <div style={{ padding: '28px 22px 0' }}>
        <Eyebrow color={R.pearl4}>COURT · حسابك</Eyebrow>
        <div style={{
          marginTop: 12, background: R.ink2,
          border: `0.5px solid ${R.hair}`, borderRadius: 16, overflow: 'hidden',
        }}>
          <RowLink
            label={<>Linked cards <VBadge>v1.2</VBadge></>}
            value={`${linkedCount} cards`}
            onClick={onLinkedCards}
          />
          <RowLink
            label="WhatsApp concierge"
            sub="PILOT · +1 201-979-4438"
            value={<span style={{ color: R.gold }}>open ›</span>}
            onClick={() => openSikkaWhatsapp({ name, linkedIds: linked })}
          />
          <RowLink
            label={<span style={{ color: R.oxblood }}>Log out</span>}
            sub="END SESSION · RETURN TO SPLASH"
            value={<span style={{ color: R.pearl3 }}>›</span>}
            onClick={onLogout}
            last
          />
        </div>
      </div>

      {/* Crest */}
      <div style={{
        padding: '36px 22px 0', textAlign: 'center',
        animation: 'r-fade 600ms 600ms both',
      }}>
        <StarDivider dim={0.4} />
        <Sub style={{
          marginTop: 18, color: R.pearl3, fontSize: 13, fontStyle: 'italic',
        }}>
          Sikka — minted in the United Arab Emirates.
        </Sub>
        <Sub style={{
          marginTop: 6, color: R.pearl4, fontSize: 13,
          fontFamily: FR.arabD, direction: 'rtl',
        }}>
          سُكَّت في الإمارات العربية المتحدة.
        </Sub>
      </div>
    </div>
  );
}

function ToggleRow({ label, sub, on, onToggle, last = false }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `0.5px solid ${R.hair}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FR.serif, fontSize: 15.5, color: R.pearl,
          letterSpacing: -0.2, fontWeight: 500, lineHeight: 1.25,
        }} dangerouslySetInnerHTML={{ __html: typeof label === 'string' ? label : '' }} />
        {typeof label !== 'string' && <div style={{
          fontFamily: FR.serif, fontSize: 15.5, color: R.pearl,
          letterSpacing: -0.2, fontWeight: 500, lineHeight: 1.25,
        }}>{label}</div>}
        {sub && <Eyebrow size={9} ls={1.4} color={R.pearl4} style={{
          marginTop: 4, textTransform: 'uppercase',
        }} dangerouslySetInnerHTML={{ __html: sub }} />}
      </div>
      <Switch on={on} onClick={onToggle} />
    </div>
  );
}

function Switch({ on, onClick }) {
  return (
    <button onClick={onClick} aria-pressed={on} style={{
      width: 46, height: 28, padding: 2, border: 'none',
      background: on
        ? `linear-gradient(180deg, ${R.goldH}, ${R.goldD})`
        : R.ink4,
      borderRadius: 999, cursor: 'pointer',
      position: 'relative', transition: 'background 200ms',
      flexShrink: 0,
      boxShadow: on ? `0 0 12px ${R.gold}55, inset 0 0 0 0.5px ${R.goldD}` : 'none',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 20 : 2,
        width: 24, height: 24, borderRadius: '50%',
        background: R.pearl, transition: 'left 220ms cubic-bezier(.2,.7,.2,1)',
        boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
      }} />
    </button>
  );
}

function RowLink({ label, value, sub, onClick, last = false }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', display: 'flex',
      width: '100%', alignItems: 'center', gap: 14,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `0.5px solid ${R.hair}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FR.serif, fontSize: 15.5, color: R.pearl,
          letterSpacing: -0.2, fontWeight: 500,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>{label}</div>
        {sub && <Eyebrow size={9} ls={1.6} color={R.pearl4} style={{ marginTop: 4 }}>{sub}</Eyebrow>}
      </div>
      <div style={{ fontFamily: FR.mono, fontSize: 13, color: R.pearl3 }}>{value}</div>
    </button>
  );
}

Object.assign(window, {
  HomeScreen, RoyalWalletCard, SettingsScreen, GoalCard,
  BottomTabNav, Num, StatTile, QuickTile,
});
