// QReward Customer — Home, My Points, Points History
const { useState: uS2, useEffect: uE2, useMemo: uM2 } = React;

/* ============ HOME DASHBOARD ============ */
const HomeScreen = ({ lang, cardStatus, onNav, animateKey, refreshKey }) => {
  const [loading, setLoading] = uS2(true);
  uE2(() => { setLoading(true); const t = setTimeout(() => setLoading(false), 700); return () => clearTimeout(t); }, [refreshKey]);
  const hour = 9;
  const greeting = hour < 12 ? (lang === 'jp' ? 'おはようございます' : 'Good morning') : (lang === 'jp' ? 'こんにちは' : 'Hello');

  const showApplyCard = cardStatus === 'notapplied' || cardStatus === 'declined';
  const quickActions = [
    { id: 'market', icon: 'redeem', label: L(lang, 'marketplace'), color: '', go: () => onNav('tab', 'redeem') },
    showApplyCard && { id: 'apply', icon: 'card', label: L(lang, 'applyForCard'), color: 'amber', go: () => onNav('push', 'mycard') },
    { id: 'link', icon: 'link', label: L(lang, 'linking'), color: 'purple', go: () => onNav('push', 'linked') },
    { id: 'card', icon: 'wallet', label: L(lang, 'myCard'), color: 'green', go: () => onNav('tab', 'card') },
  ].filter(Boolean);

  return (
    <div className="scr scr-pad-status">
      {/* sticky top bar */}
      <div className="tbar">
        <Wordmark size={22} />
        <button className="tbar-action-icon" onClick={() => onNav('push', 'notifications')}>
          <Icon n="bell" s={21} />
          <span className="tbar-action-dot"></span>
        </button>
      </div>
      <div className="home-scroll">
        <div style={{ padding: '4px 20px 8px' }}>
          <div className="muted" style={{ fontSize: 14 }}>{greeting},</div>
          <div className="h2">{lang === 'jp' ? `${DATA.user.nameJp}さん` : DATA.user.name}</div>
        </div>

        {/* 3D card hero */}
        <div style={{ padding: '6px 20px 0' }}>
          <QCard balance={DATA.balance} lifecard={DATA.lifecard} qualia={DATA.qualia}
            status={cardStatus === 'locked' ? 'locked' : 'active'} lang={lang} loading={loading}
            animateKey={animateKey} onTap={() => onNav('tab', 'points')} />
        </div>

        {/* Quick actions */}
        <div className="qab-row" style={quickActions.length === 3 ? { gridTemplateColumns: 'repeat(3,1fr)' } : null}>
          {quickActions.map(a => (
            <button key={a.id} className="qab" onClick={a.go}>
              <span className={`qab-icon ${a.color ? 'qab-icon-' + a.color : ''}`}><Icon n={a.icon} s={18} /></span>
              <span className="qab-label">{a.label}</span>
            </button>
          ))}
        </div>

        {/* LifeCard status */}
        <div className="section-title">{lang === 'jp' ? 'LifeCard 申請状況' : 'LifeCard application'}</div>
        <div style={{ padding: '0 16px' }}>
          <button className="surface" style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, width: '100%', textAlign: 'left' }} onClick={() => onNav('tab', 'card')}>
            <div className="list-row-icon" style={{ width: 40, height: 40, background: cardStatus === 'declined' ? 'var(--red-50)' : cardStatus === 'activated' ? 'var(--green-50)' : 'var(--info-50)', color: cardStatus === 'declined' ? 'var(--red-600)' : cardStatus === 'activated' ? 'var(--green-600)' : 'var(--info-600)' }}>
              <Icon n="card" s={20} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>{lang === 'jp' ? 'LifeCard クレジットカード' : 'LifeCard Credit Card'}</div>
              {cardStatus === 'submitted' && <StatusPill kind="submitted" label={lang === 'jp' ? '審査中' : 'Submitted'} icon="clock" />}
              {cardStatus === 'activated' && <StatusPill kind="activated" label={lang === 'jp' ? '有効' : 'Activated'} icon="check" />}
              {cardStatus === 'declined' && <StatusPill kind="declined" label={lang === 'jp' ? '否認' : 'Declined'} icon="info" />}
              {cardStatus === 'notapplied' && <span className="muted" style={{ fontSize: 13 }}>{lang === 'jp' ? '未申請 · 申請して特典を獲得' : 'Not applied · apply to start earning'}</span>}
              {cardStatus === 'submitted' && <span className="muted" style={{ fontSize: 12, marginLeft: 8 }}>{DATA.card.submittedDate}</span>}
            </div>
            <Icon n="chevR" s={18} c="var(--ink-300)" />
          </button>
        </div>

        {/* Featured offers */}
        <div className="section-title-row">
          <span className="title">{L(lang, 'featuredOffers')}</span>
          <button className="action" onClick={() => onNav('tab', 'redeem')}>{L(lang, 'viewAll')}</button>
        </div>
        <div className="offers-scroll">
          {DATA.offers.map(o => (
            <button key={o.id} className={`offer-card ${o.theme}`} onClick={() => onNav('tab', 'redeem')}>
              <span className="offer-card-tag">{o.tag}</span>
              <div className="offer-card-body">
                <div className="offer-card-name">{o.name}</div>
                <div className="offer-card-scope">{o.scope}</div>
              </div>
            </button>
          ))}
        </div>

        {/* Recent activity */}
        <div className="section-title-row">
          <span className="title">{L(lang, 'recentActivity')}</span>
          <button className="action" onClick={() => onNav('push', 'history')}>{L(lang, 'viewAll')}</button>
        </div>
        <div className="list" style={{ marginBottom: 16 }}>
          {DATA.activity.slice(0, 5).map(a => <ActivityRow key={a.id} a={a} lang={lang} />)}
        </div>
      </div>
      <style>{`
        .home-scroll { flex: 1; overflow-y: auto; padding-bottom: 100px; }
      `}</style>
    </div>
  );
};

const ActivityRow = ({ a, lang, showBal = true }) => {
  const tagMap = {
    lifecard: { cls: 'lifecard', label: 'LifeCard' },
    qualia: { cls: 'qualia', label: 'QUALIA' },
    admin: { cls: 'admin', label: lang === 'jp' ? '調整' : 'Admin' },
    redeem: { cls: 'redeem', label: lang === 'jp' ? '交換' : 'Redeem' },
  };
  const tag = tagMap[a.src] || tagMap.redeem;
  const pos = a.amt > 0;
  return (
    <div className="activity-row">
      <div className="activity-row-body">
        <div className="activity-row-desc">{a.desc}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className={`activity-tag activity-tag-${tag.cls}`}>{tag.label}</span>
          <span className="activity-row-date">{a.date}</span>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className={`activity-row-amt ${pos ? 'pos' : 'neg'}`}>{pos ? '+' : '−'}{fmt(Math.abs(a.amt))}<span className="r-glyph" style={{ fontSize: '0.7em' }}>&thinsp;r</span></div>
        {showBal && <div className="activity-row-bal">{lang === 'jp' ? '残高' : 'Bal'} {fmt(a.bal)}</div>}
      </div>
    </div>
  );
};

/* ============ MY POINTS ============ */
const MyPointsScreen = ({ lang, onNav }) => {
  const total = DATA.balance;
  const lcPct = Math.round(DATA.lifecard / total * 100);
  const qPct = 100 - lcPct;
  const [anim, setAnim] = uS2(0);
  uE2(() => { const t = setTimeout(() => setAnim(1), 100); return () => clearTimeout(t); }, []);

  // pie geometry
  const r = 42, c = 2 * Math.PI * r;
  const lcLen = c * (DATA.lifecard / total) * anim;
  const qLen = c * (DATA.qualia / total) * anim;

  return (
    <div className="scr scr-pad-status">
      <TopBar title={L(lang, 'myPoints')} lang={lang} />
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 100 }}>
        <div style={{ textAlign: 'center', padding: '12px 20px 20px' }}>
          <div className="muted" style={{ fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{L(lang, 'totalBalance')}</div>
          <div className="balance-big" style={{ marginTop: 8 }}>{fmt(total)}<span className="r-glyph">r</span></div>
        </div>

        {/* Pie + legend */}
        <div className="pie-wrap">
          <svg className="pie-svg" viewBox="0 0 100 100">
            <circle cx="50" cy="50" r={r} fill="none" stroke="var(--surface-2)" strokeWidth="14" />
            <circle cx="50" cy="50" r={r} fill="none" stroke="#0ea5e9" strokeWidth="14"
              strokeDasharray={`${lcLen} ${c}`} transform="rotate(-90 50 50)" style={{ transition: 'stroke-dasharray 700ms ease' }} strokeLinecap="round" />
            <circle cx="50" cy="50" r={r} fill="none" stroke="#7c3aed" strokeWidth="14"
              strokeDasharray={`${qLen} ${c}`} strokeDashoffset={-lcLen} transform="rotate(-90 50 50)" style={{ transition: 'stroke-dasharray 700ms ease, stroke-dashoffset 700ms ease' }} strokeLinecap="round" />
          </svg>
          <div className="pie-legend">
            <div className="pie-legend-item">
              <span className="pie-legend-swatch" style={{ background: '#0ea5e9' }}></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>LifeCard <span className="muted" style={{ fontWeight: 400 }}>· {lcPct}%</span></div>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)', fontFeatureSettings: '"tnum"' }}>{fmt(DATA.lifecard)} r</div>
              </div>
            </div>
            <div className="pie-legend-item">
              <span className="pie-legend-swatch" style={{ background: '#7c3aed' }}></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>QUALIA <span className="muted" style={{ fontWeight: 400 }}>· {qPct}%</span></div>
                <div style={{ fontSize: 13, color: 'var(--fg-muted)', fontFeatureSettings: '"tnum"' }}>{fmt(DATA.qualia)} r</div>
              </div>
            </div>
          </div>
        </div>

        {/* Sources */}
        <div className="section-title-row">
          <span className="title">{lang === 'jp' ? 'ポイント元' : 'Sources'}</span>
          <button className="action" onClick={() => onNav('push', 'history')}>{lang === 'jp' ? 'すべての履歴' : 'All activity'}</button>
        </div>
        <div style={{ padding: '0 16px' }}>
          {DATA.sources.map(s => (
            <button key={s.id} className="linked-tile" style={{ margin: '0 0 10px', width: '100%' }} onClick={() => onNav('push', 'history', { filter: s.name })}>
              <div className="linked-logo" style={{ background: s.color }}>{s.letter}</div>
              <div className="linked-body">
                <div className="linked-name">{s.name}</div>
                <div className="linked-meta">{lang === 'jp' ? '最終同期' : 'Last sync'} {s.lastSync}</div>
                <div className="linked-meta" style={{ marginTop: 2 }}>{lang === 'jp' ? '累計' : 'Lifetime'}: {fmt(s.lifetime)} r</div>
              </div>
              <Icon n="chevR" s={18} c="var(--ink-300)" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

/* ============ POINTS HISTORY ============ */
const PointsHistoryScreen = ({ lang, onBack, initFilter }) => {
  const [filter, setFilter] = uS2(initFilter || 'All');
  const [query, setQuery] = uS2('');
  const filters = ['All', 'LifeCard', 'QUALIA', lang === 'jp' ? '交換' : 'Marketplace', lang === 'jp' ? '調整' : 'Admin adjusted'];
  const all = [
    ...DATA.activity,
    { id: 'h7', src: 'qualia', type: 'earn', desc: 'QUALIA monthly batch — April', amt: 3210, bal: 25440, date: '2026/04/15 14:18' },
    { id: 'h8', src: 'redeem', type: 'redeem', desc: 'MUJI Home Set ×1', amt: -4500, bal: 22230, date: '2026/04/10 11:02' },
    { id: 'h9', src: 'lifecard', type: 'earn', desc: 'LifeCard CSV import — April', amt: 980, bal: 26730, date: '2026/04/05 10:18' },
  ];
  const filtered = all.filter(a => {
    if (filter === 'LifeCard' && a.src !== 'lifecard') return false;
    if (filter === 'QUALIA' && a.src !== 'qualia') return false;
    if ((filter === 'Marketplace' || filter === '交換') && a.src !== 'redeem') return false;
    if ((filter === 'Admin adjusted' || filter === '調整') && a.src !== 'admin') return false;
    if (query && !a.desc.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });
  return (
    <div className="scr scr-pad-status">
      <TopBar title={lang === 'jp' ? 'ポイント履歴' : 'Points history'} onBack={onBack} lang={lang} />
      <div className="search">
        <Icon n="search" s={16} />
        <input value={query} onChange={e => setQuery(e.target.value)} placeholder={lang === 'jp' ? '説明・注文ID・バッチIDで検索' : 'Search description, order ID, batch ID'} />
      </div>
      <div className="cat-strip" style={{ paddingTop: 0 }}>
        {filters.map(f => <button key={f} className={`cat-chip ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>{f}</button>)}
      </div>
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 30 }}>
        {filtered.length === 0
          ? <div className="empty-state"><div className="empty-state-icon"><Icon n="search" s={24} /></div><div className="empty-state-title">{lang === 'jp' ? '該当なし' : 'No items match'}</div><div className="empty-state-body">{lang === 'jp' ? 'フィルターをクリアしてください' : 'Try clearing the filter'}</div></div>
          : <div className="list" style={{ margin: '0 16px' }}>{filtered.map(a => <ActivityRow key={a.id} a={a} lang={lang} />)}</div>}
        {filtered.length > 0 && <div style={{ textAlign: 'center', padding: 20, fontSize: 12, color: 'var(--fg-subtle)' }}>· {lang === 'jp' ? '履歴の最後' : 'End of history'} ·</div>}
      </div>
    </div>
  );
};

Object.assign(window, { HomeScreen, MyPointsScreen, PointsHistoryScreen, ActivityRow });
