// QReward Customer — My Card (4 states), Linked accounts
const { useState: uS3, useEffect: uE3 } = React;

/* ============ MY CARD ============ */
const MyCardScreen = ({ lang, status, onBack, asTab, toast }) => {
  // status: notapplied | submitted | activated | declined
  return (
    <div className="scr scr-pad-status">
      <TopBar title={lang === 'jp' ? 'マイカード' : 'My Card'} onBack={asTab ? null : onBack} lang={lang} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: asTab ? 100 : 40 }}>
        {/* Shared header: card visual */}
        <div style={{ padding: '8px 20px 16px' }}>
          <div className="credit-card" style={{ opacity: status === 'activated' ? 1 : 0.92 }}>
            <div className="credit-card-sheen"></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', position: 'relative' }}>
              <div className="qcard-cobrand" style={{ color: 'white' }}>LifeCard <span className="qcard-cobrand-sep"></span> QUALIA</div>
              {status === 'activated' && <StatusPill kind="activated" label={lang === 'jp' ? '有効' : 'Active'} icon="check" />}
              {status === 'submitted' && <span className="pill" style={{ background: 'rgba(255,255,255,0.2)', color: 'white' }}><Icon n="clock" s={11} sw={2.4} />{lang === 'jp' ? '審査中' : 'In review'}</span>}
            </div>
            <div className="credit-card-chip"></div>
            <div style={{ position: 'relative' }}>
              <div className="credit-card-number">{status === 'activated' ? DATA.card.masked : '•••• •••• •••• ••••'}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
                <div>
                  <div className="credit-card-label">{lang === 'jp' ? 'カード名義' : 'Card holder'}</div>
                  <div className="credit-card-val">{status === 'activated' ? DATA.card.holder : '—'}</div>
                </div>
                <div>
                  <div className="credit-card-label">{lang === 'jp' ? '有効期限' : 'Expires'}</div>
                  <div className="credit-card-val">{status === 'activated' ? DATA.card.expiry : '••/••'}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {status === 'notapplied' && <CardNotApplied lang={lang} toast={toast} />}
        {status === 'submitted' && <CardSubmitted lang={lang} />}
        {status === 'activated' && <CardActivated lang={lang} />}
        {status === 'declined' && <CardDeclined lang={lang} toast={toast} />}
      </div>

      <style>{`
        .credit-card { aspect-ratio: 1.585/1; border-radius: 18px; padding: 18px; position: relative; overflow: hidden;
          background: radial-gradient(circle at 80% 0%, rgba(255,200,140,0.18), transparent 50%), linear-gradient(135deg, #131e4a, #1b2d6f 55%, #0a1330);
          color: white; display: flex; flex-direction: column; justify-content: space-between;
          box-shadow: 0 18px 34px -12px rgba(10,19,48,0.5); }
        .credit-card-sheen { position: absolute; inset: 0; background: linear-gradient(115deg, transparent 40%, rgba(255,255,255,0.12) 50%, transparent 60%); }
        .credit-card-chip { width: 34px; height: 26px; border-radius: 5px; background: linear-gradient(135deg,#e6c275,#b8923f); position: relative; z-index: 1; }
        .credit-card-number { font-family: var(--font-mono); font-size: 17px; letter-spacing: 0.12em; font-weight: 500; }
        .credit-card-label { font-size: 8px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.6; }
        .credit-card-val { font-size: 12px; font-weight: 600; letter-spacing: 0.04em; margin-top: 2px; }
      `}</style>
    </div>
  );
};

const benefits = (lang) => [
  { icon: 'spark', t: lang === 'jp' ? '利用金額の最大2%をポイント還元' : 'Up to 2% points back on every purchase' },
  { icon: 'gift', t: lang === 'jp' ? '提携店舗で限定オファー' : 'Exclusive offers at partner stores' },
  { icon: 'shield', t: lang === 'jp' ? '年会費無料・不正利用補償付き' : 'No annual fee · fraud protection included' },
];

const CardNotApplied = ({ lang, toast }) => {
  const [showInterstitial, setShow] = uS3(false);
  if (showInterstitial) return (
    <div style={{ textAlign: 'center', padding: '40px 32px' }}>
      <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--green-50)', display: 'grid', placeItems: 'center', margin: '0 auto 18px', animation: 'pop 500ms ease' }}>
        <Icon n="check" s={36} c="var(--green-600)" sw={2.4} />
      </div>
      <div className="h2">{lang === 'jp' ? '申請を受け付けました' : 'Application submitted'}</div>
      <div className="muted" style={{ fontSize: 15, marginTop: 10, lineHeight: 1.5 }}>{lang === 'jp' ? 'LifeCardの審査結果は、次回のデータ更新時に反映されます。' : "We'll update your status when LifeCard's daily report arrives."}</div>
      <div style={{ marginTop: 24 }}><Btn block onClick={() => toast(lang === 'jp' ? 'マイカードで状況を確認できます' : 'Track it in My Card')}>{lang === 'jp' ? 'マイカードで追跡' : 'Track in My Card'}</Btn></div>
      <style>{`@keyframes pop { from { transform: scale(0.5); opacity: 0; } to { transform: scale(1); opacity: 1; } }`}</style>
    </div>
  );
  return (
    <div>
      <div className="section-title">{lang === 'jp' ? '特典' : 'Benefits'}</div>
      <div style={{ padding: '0 16px' }}>
        {benefits(lang).map((b, i) => (
          <div key={i} className="surface" style={{ display: 'flex', gap: 12, padding: 14, marginBottom: 10, alignItems: 'center' }}>
            <div className="list-row-icon" style={{ width: 38, height: 38, background: 'var(--amber-100)', color: 'var(--amber-600)' }}><Icon n={b.icon} s={18} /></div>
            <div style={{ fontSize: 14, lineHeight: 1.45, flex: 1 }}>{b.t}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: '20px 20px 8px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Btn block onClick={() => setShow(true)}>{lang === 'jp' ? '今すぐ申請' : 'Apply now'}</Btn>
        <Btn block variant="ghost">{lang === 'jp' ? '詳しく見る' : 'Learn more'}</Btn>
      </div>
      <div className="muted" style={{ fontSize: 12, textAlign: 'center', padding: '0 32px', lineHeight: 1.5 }}>
        {lang === 'jp' ? '「今すぐ申請」をタップすると、LifeCardの申請フォームが開きます。' : 'Apply now opens LifeCard\'s secure application form in an in-app browser.'}
      </div>
    </div>
  );
};

const Timeline = ({ items }) => (
  <div className="stepper" style={{ marginTop: 8 }}>
    {items.map((it, i) => (
      <div key={i} className={`step ${it.state}`}>
        <div className={`step-dot ${it.state}`}>{it.state === 'done' ? <Icon n="check" s={12} sw={3} /> : it.state === 'active' ? <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff' }}></span> : it.state === 'failed' ? <Icon n="x" s={12} sw={3} /> : null}</div>
        <div className="step-body">
          <div className="step-title">{it.title}</div>
          {it.time && <div className="step-time">{it.time}</div>}
          {it.meta && <div className="step-meta">{it.meta}</div>}
        </div>
      </div>
    ))}
  </div>
);

const CardSubmitted = ({ lang }) => (
  <div>
    <div style={{ padding: '0 20px 4px', display: 'flex', justifyContent: 'center' }}>
      <StatusPill kind="submitted" label={lang === 'jp' ? '審査中' : 'Submitted'} icon="clock" />
    </div>
    <div className="section-title">{lang === 'jp' ? '申請状況' : 'Application timeline'}</div>
    <Timeline items={[
      { state: 'done', title: lang === 'jp' ? '申請（QRewardで）' : 'Applied (in QReward)', time: DATA.card.submittedDate + ' JST' },
      { state: 'active', title: lang === 'jp' ? '審査待ち' : 'Awaiting decision', meta: lang === 'jp' ? 'LifeCardの日次レポート到着時に更新されます。' : "We update this status when LifeCard's daily report arrives." },
    ]} />
    <div className="banner" style={{ marginTop: 16 }}>
      <Icon n="info" s={18} />
      <div>{lang === 'jp' ? '審査には数営業日かかる場合があります。' : 'Decisions can take a few business days. We\'ll notify you the moment it changes.'}</div>
    </div>
  </div>
);

const CardActivated = ({ lang }) => (
  <div>
    <div style={{ padding: '0 20px 4px', display: 'flex', justifyContent: 'center' }}>
      <StatusPill kind="activated" label={lang === 'jp' ? '有効' : 'Activated'} icon="check" />
    </div>
    <div className="section-title">{lang === 'jp' ? '申請状況' : 'Application timeline'}</div>
    <Timeline items={[
      { state: 'done', title: lang === 'jp' ? '申請（QRewardで）' : 'Applied (in QReward)', time: DATA.card.submittedDate + ' JST' },
      { state: 'done', title: lang === 'jp' ? '有効化' : 'Activated by LifeCard', time: DATA.card.activatedDate + ' JST' },
    ]} />
    <div className="section-title">{lang === 'jp' ? 'カード詳細' : 'Card details'}</div>
    <div className="list" style={{ margin: '0 16px' }}>
      <div className="list-row"><div className="list-row-body"><div className="list-row-title">{lang === 'jp' ? 'カード番号' : 'Card number'}</div></div><div className="list-row-trail mono">{DATA.card.masked}</div></div>
      <div className="list-row"><div className="list-row-body"><div className="list-row-title">{lang === 'jp' ? '有効期限' : 'Expiry'}</div></div><div className="list-row-trail mono">{DATA.card.expiry}</div></div>
      <div className="list-row"><div className="list-row-body"><div className="list-row-title">{lang === 'jp' ? 'カード名義' : 'Cardholder'}</div></div><div className="list-row-trail">{DATA.card.holder}</div></div>
    </div>
  </div>
);

const CardDeclined = ({ lang, toast }) => (
  <div>
    <div style={{ padding: '0 20px 4px', display: 'flex', justifyContent: 'center' }}>
      <StatusPill kind="declined" label={lang === 'jp' ? '否認' : 'Declined'} icon="info" />
    </div>
    <div style={{ padding: '16px 20px', textAlign: 'center' }}>
      <div className="h3" style={{ marginBottom: 8 }}>{lang === 'jp' ? '今回はご希望に添えませんでした' : "Your application wasn't successful this time"}</div>
      <div className="muted" style={{ fontSize: 14, lineHeight: 1.55 }}>{lang === 'jp' ? '理由はさまざまです。時間をおいて再度お申し込みいただけます。' : 'There are many possible reasons. You can apply again, and we\'re here to help.'}</div>
      <button style={{ color: 'var(--brand-600)', fontWeight: 600, fontSize: 14, marginTop: 10 }}>{lang === 'jp' ? 'よくある理由を見る' : 'See common reasons →'}</button>
    </div>
    <div style={{ padding: '8px 20px' }}>
      <Btn block onClick={() => toast(lang === 'jp' ? '申請フローを開きます' : 'Re-opening application')}>{lang === 'jp' ? '再申請する' : 'Apply again'}</Btn>
    </div>
  </div>
);

/* ============ LINKED ACCOUNTS ============ */
const LinkedAccountsScreen = ({ lang, onBack, toast }) => {
  const [sources, setSources] = uS3([
    { id: 'qualia', name: 'QUALIA', linked: true, last: '2026/06/07 09:14', color: '#7c3aed', letter: 'Q' },
    { id: 'lifecard', name: 'LifeCard', linked: true, last: '2026/06/07 10:31', color: '#0ea5e9', letter: 'L' },
    { id: 'rakuten', name: 'Rakuten', linked: false, last: null, color: '#bf0000', letter: 'R' },
  ]);
  const [linking, setLinking] = uS3(null); // id being linked (browser open)
  const [unlinkTarget, setUnlink] = uS3(null);

  const doLink = (id) => {
    setLinking(id);
    setTimeout(() => {
      setSources(s => s.map(x => x.id === id ? { ...x, linked: true, last: '2026/06/08 just now' } : x));
      setLinking(null);
      toast(lang === 'jp' ? '連携しました' : 'Linked successfully');
    }, 1800);
  };
  const doUnlink = () => {
    setSources(s => s.map(x => x.id === unlinkTarget ? { ...x, linked: false, last: null } : x));
    toast(lang === 'jp' ? '連携を解除しました' : 'Unlinked');
    setUnlink(null);
  };

  return (
    <div className="scr scr-pad-status">
      <TopBar title={lang === 'jp' ? '連携アカウント' : 'Linked accounts'} onBack={onBack} lang={lang} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 30 }}>
        <div className="muted" style={{ fontSize: 13, padding: '4px 20px 14px', lineHeight: 1.5 }}>
          {lang === 'jp' ? '提携先を連携すると、ポイントが自動で同期されます。' : 'Link partner accounts to sync your points automatically.'}
        </div>
        {sources.map(s => (
          <div key={s.id} className="linked-tile">
            <div className="linked-logo" style={{ background: s.color }}>{s.letter}</div>
            <div className="linked-body">
              <div className="linked-name">{s.name}</div>
              {s.linked
                ? <div style={{ marginTop: 4 }}><StatusPill kind="linked" label={lang === 'jp' ? '連携済み' : 'Linked'} icon="check" /></div>
                : <div style={{ marginTop: 4 }}><StatusPill kind="unlinked" label={lang === 'jp' ? '未連携' : 'Not linked'} /></div>}
              {s.last && <div className="linked-meta" style={{ marginTop: 4 }}>{lang === 'jp' ? '最終同期' : 'Last sync'} {s.last}</div>}
            </div>
            {linking === s.id
              ? <div className="linked-cta locked" style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span className="spin-mini"></span>{lang === 'jp' ? '連携中' : 'Linking'}</div>
              : s.linked
                ? <button className="linked-cta unlink" onClick={() => setUnlink(s.id)}>{lang === 'jp' ? '解除' : 'Unlink'}</button>
                : <button className="linked-cta link" onClick={() => doLink(s.id)}>{lang === 'jp' ? '連携' : 'Link'}</button>}
          </div>
        ))}
        <div className="banner" style={{ marginTop: 6 }}>
          <Icon n="info" s={18} />
          <div>{lang === 'jp' ? '連携時は提携先の認証画面が開きます。認証情報がQRewardに保存されることはありません。' : "Linking opens the partner's secure sign-in. We never store your partner credentials."}</div>
        </div>
      </div>

      <Sheet open={!!unlinkTarget} onClose={() => setUnlink(null)} title={lang === 'jp' ? '連携を解除しますか？' : `Unlink ${sources.find(s => s.id === unlinkTarget)?.name}?`}>
        <div className="muted" style={{ fontSize: 14, lineHeight: 1.5, marginBottom: 18 }}>
          {lang === 'jp' ? '再連携するまで、新しいポイントは付与されません。' : "You'll stop earning new points from this source until you link again."}
        </div>
        <Btn block variant="danger" onClick={doUnlink}>{lang === 'jp' ? '連携を解除' : 'Unlink'}</Btn>
        <button style={{ width: '100%', padding: 14, color: 'var(--fg-muted)', fontWeight: 600, marginTop: 4 }} onClick={() => setUnlink(null)}>{lang === 'jp' ? 'キャンセル' : 'Cancel'}</button>
      </Sheet>
      <style>{`.spin-mini { width: 13px; height: 13px; border: 2px solid var(--ink-200); border-top-color: var(--fg-muted); border-radius: 50%; animation: spin 700ms linear infinite; }`}</style>
    </div>
  );
};

Object.assign(window, { MyCardScreen, LinkedAccountsScreen });
