/* MaiAgent Partner Portal — 客戶成功中心 */

const CSC_TABS = [
  { id: 'licenses', key: 'csc.tab.licenses' },
  { id: 'renewals', key: 'csc.tab.renewals' },
  { id: 'alerts',   key: 'csc.tab.alerts'   },
];

// ── Helpers ─────────────────────────────────────────────────────
function cscLicenseExpiry(cl) {
  if (!cl.licenseEnd) return { daysLeft: null, status: 'pending' };
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const end = new Date(cl.licenseEnd);
  const daysLeft = Math.ceil((end - today) / 86400000);
  const status = daysLeft < 0 ? 'expired' : daysLeft <= 30 ? 'urgent' : daysLeft <= 90 ? 'soon' : 'safe';
  return { daysLeft: Math.max(0, daysLeft), status };
}

// ── Health badge ─────────────────────────────────────────────────
const CscHealthBadge = ({ health, lang }) => {
  const MAP = {
    healthy:   { zh: '健康',   en: 'Healthy',   color: '#059669', bg: '#ECFDF5', border: '#A7F3D0' },
    watch:     { zh: '觀察中', en: 'Watch',      color: '#D97706', bg: '#FFFBEB', border: '#FDE68A' },
    attention: { zh: '需關注', en: 'Attention',  color: '#DC2626', bg: '#FEF2F2', border: '#FECACA' },
    pending:   { zh: '待開通', en: 'Pending',    color: '#6B7280', bg: '#F9FAFB', border: '#E5E7EB' },
  };
  const c = MAP[health] || MAP.pending;
  return (
    <span style={{ background: c.bg, color: c.color, border: `1px solid ${c.border}`, fontSize: 11, fontWeight: 700, padding: '3px 9px', borderRadius: 99, whiteSpace: 'nowrap' }}>
      {lang === 'zh' ? c.zh : c.en}
    </span>
  );
};

// ── Mini usage bar ───────────────────────────────────────────────
const CscUsageBar = ({ used, quota, lang }) => {
  if (!quota) return null;
  const pct = Math.min(100, Math.round((used / quota) * 100));
  const color = pct >= 90 ? '#EF4444' : pct >= 70 ? '#F59E0B' : '#26C281';
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5, fontSize: 11.5 }}>
        <span style={{ color: 'var(--mai-fg-3)' }}>{lang === 'zh' ? '本月使用量' : 'Monthly usage'}</span>
        <span style={{ fontWeight: 700, color }}>{pct}%&ensp;<span style={{ fontWeight: 400, color: 'var(--mai-fg-3)' }}>{used?.toLocaleString()} / {quota?.toLocaleString()}</span></span>
      </div>
      <div style={{ height: 5, background: 'var(--mai-border)', borderRadius: 99, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct}%`, background: color, borderRadius: 99 }} />
      </div>
    </div>
  );
};

// ── Mini sparkline (4-week trend) ─────────────────────────────────
const CscSparkline = ({ data }) => {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data);
  const w = 60, h = 24, step = w / (data.length - 1);
  const pts = data.map((v, i) => `${i * step},${h - (v / max) * h}`).join(' ');
  return (
    <svg width={w} height={h} style={{ overflow: 'visible' }}>
      <polyline points={pts} fill="none" stroke="#1F4FFF" strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
};

// ── License card ─────────────────────────────────────────────────
const CscLicenseCard = ({ cl, lang, t }) => {
  const { daysLeft, status } = cscLicenseExpiry(cl);
  const expiryColor = { expired: '#DC2626', urgent: '#D97706', soon: '#6366F1', safe: 'var(--mai-fg-3)', pending: 'var(--mai-fg-3)' }[status];

  return (
    <div className="card--lift" style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 14, padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--mai-fg)', lineHeight: 1.3 }}>{cl.company[lang]}</div>
          <div style={{ fontSize: 11.5, color: 'var(--mai-fg-3)', marginTop: 2 }}>{cl.plan}</div>
        </div>
        <CscHealthBadge health={cl.health} lang={lang} />
      </div>

      {/* Org ID */}
      {cl.orgId && (
        <div style={{ fontFamily: 'ui-monospace,monospace', fontSize: 11, color: 'var(--mai-fg-3)', background: '#F8FAFC', padding: '4px 9px', borderRadius: 7, border: '1px solid var(--mai-border)' }}>
          {cl.orgId}
        </div>
      )}

      {/* Usage bar */}
      {cl.monthlyQuota && <CscUsageBar used={cl.monthlyUsed} quota={cl.monthlyQuota} lang={lang} />}

      {/* Trend row */}
      {cl.trend !== null && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
            <Icon name={cl.trend >= 0 ? 'arrow-up' : 'arrow-down'} size={12} style={{ color: cl.trend >= 0 ? '#26C281' : '#EF4444' }} />
            <span style={{ color: cl.trend >= 0 ? '#26C281' : '#EF4444', fontWeight: 700 }}>
              {cl.trend >= 0 ? '+' : ''}{cl.trend.toFixed(1)}%
            </span>
            <span style={{ color: 'var(--mai-fg-3)' }}>{t('csc.vs_last')}</span>
          </div>
          {cl.weeklyTrend && <CscSparkline data={cl.weeklyTrend} />}
        </div>
      )}

      {/* Health note */}
      {cl.healthNote && (
        <div style={{ fontSize: 11.5, color: cl.health === 'attention' ? '#DC2626' : '#D97706', background: cl.health === 'attention' ? '#FEF2F2' : '#FFFBEB', padding: '7px 10px', borderRadius: 8, lineHeight: 1.45 }}>
          {lang === 'zh' ? cl.healthNote.zh : cl.healthNote.en}
        </div>
      )}

      {/* Footer */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 6, borderTop: '1px solid var(--mai-border)', marginTop: 2 }}>
        <div style={{ fontSize: 12, color: expiryColor, fontWeight: 600 }}>
          {status === 'pending' ? '—'
           : status === 'expired' ? t('csc.expired')
           : `${daysLeft} ${t('csc.days_left')}`}
          {cl.licenseEnd && status !== 'pending' && (
            <span style={{ color: 'var(--mai-fg-3)', fontWeight: 400, marginLeft: 6 }}>{cl.licenseEnd}</span>
          )}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {(status === 'urgent' || status === 'soon') && (
            <Btn variant="primary" size="sm">{t('csc.action.followup')}</Btn>
          )}
          <Btn variant="ghost" size="sm">{t('csc.action.contact')}</Btn>
        </div>
      </div>
    </div>
  );
};

// ── Renewal row ──────────────────────────────────────────────────
const CscRenewalRow = ({ cl, lang, t }) => {
  const { daysLeft, status } = cscLicenseExpiry(cl);
  const urgColor = { expired: '#DC2626', urgent: '#D97706', soon: '#6366F1', safe: '#26C281' }[status] || '#6B7280';
  const urgBg    = { expired: '#FEF2F2', urgent: '#FFFBEB', soon: '#EEF2FF', safe: '#F0FDF4' }[status] || '#F9FAFB';

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 20px', borderBottom: '1px solid var(--mai-border)' }}>
      <div style={{ width: 54, height: 54, borderRadius: 12, background: urgBg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <div style={{ fontSize: 17, fontWeight: 800, color: urgColor, lineHeight: 1 }}>{daysLeft ?? '—'}</div>
        <div style={{ fontSize: 9, fontWeight: 700, color: urgColor, textTransform: 'uppercase', marginTop: 1 }}>{lang === 'zh' ? '天' : 'days'}</div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--mai-fg)' }}>{cl.company[lang]}</div>
        <div style={{ fontSize: 12, color: 'var(--mai-fg-3)', marginTop: 2 }}>
          {cl.plan} · {lang === 'zh' ? '到期' : 'Expires'} {cl.licenseEnd}
        </div>
        {cl.monthlyQuota && (
          <div style={{ fontSize: 11.5, color: 'var(--mai-fg-3)', marginTop: 3 }}>
            {lang === 'zh' ? '本月用量' : 'Usage'} {cl.monthlyUsed?.toLocaleString()} / {cl.monthlyQuota?.toLocaleString()}
          </div>
        )}
      </div>
      <CscHealthBadge health={cl.health} lang={lang} />
      <Btn variant="primary" size="sm">{t('csc.action.followup_sm')}</Btn>
    </div>
  );
};

// ── Alert row ────────────────────────────────────────────────────
const CscAlertRow = ({ cl, lang, t }) => {
  const iconName  = cl.health === 'attention' ? 'alert' : 'eye';
  const iconColor = cl.health === 'attention' ? '#DC2626' : '#D97706';
  const iconBg    = cl.health === 'attention' ? '#FEF2F2' : '#FFFBEB';

  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, padding: '14px 20px', borderBottom: '1px solid var(--mai-border)' }}>
      <div style={{ width: 38, height: 38, borderRadius: 10, background: iconBg, display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>
        <Icon name={iconName} size={16} style={{ color: iconColor }} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--mai-fg)', marginBottom: 4 }}>{cl.company[lang]}</div>
        <div style={{ fontSize: 12.5, color: iconColor, lineHeight: 1.45 }}>
          {lang === 'zh' ? cl.healthNote?.zh : cl.healthNote?.en}
        </div>
        {cl.trend !== null && cl.monthlyQuota && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, fontSize: 12 }}>
            <span style={{ color: 'var(--mai-fg-3)' }}>
              {lang === 'zh' ? '本月' : 'Month'} {cl.monthlyUsed?.toLocaleString()} / {cl.monthlyQuota?.toLocaleString()}
            </span>
            <span style={{ color: cl.trend >= 0 ? '#26C281' : '#EF4444', fontWeight: 700 }}>
              {cl.trend >= 0 ? '+' : ''}{cl.trend.toFixed(1)}% {t('csc.vs_last')}
            </span>
          </div>
        )}
      </div>
      <Btn variant="ghost" size="sm">{t('csc.action.contact')}</Btn>
    </div>
  );
};

// ── Main page ─────────────────────────────────────────────────────
const CustomerSuccessPage = ({ t, lang }) => {
  const [tab, setTab] = React.useState('licenses');

  const withExpiry = CUSTOMER_LICENSES.filter(cl => cl.licenseEnd);
  const renewalsSorted = [...withExpiry].sort((a, b) => {
    const dA = cscLicenseExpiry(a).daysLeft ?? 9999;
    const dB = cscLicenseExpiry(b).daysLeft ?? 9999;
    return dA - dB;
  });

  const urgentGroup = renewalsSorted.filter(cl => ['expired','urgent'].includes(cscLicenseExpiry(cl).status));
  const soonGroup   = renewalsSorted.filter(cl => cscLicenseExpiry(cl).status === 'soon');
  const safeGroup   = renewalsSorted.filter(cl => cscLicenseExpiry(cl).status === 'safe');
  const alertsList  = CUSTOMER_LICENSES.filter(cl => cl.health === 'attention' || cl.health === 'watch');

  const counts = {
    licenses: CUSTOMER_LICENSES.length,
    renewals: urgentGroup.length + soonGroup.length,
    alerts:   alertsList.length,
  };

  const statCards = [
    { label: t('csc.stat.customers'), value: CUSTOMER_LICENSES.filter(cl => cl.health !== 'pending').length, icon: 'users',  color: '#1F4FFF' },
    { label: t('csc.stat.expiring30'), value: urgentGroup.length, icon: 'clock',  color: '#D97706' },
    { label: t('csc.stat.alerts'),     value: alertsList.length,  icon: 'alert',  color: '#DC2626' },
  ];

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-header__title">
          <div className="page-header__eyebrow">{lang === 'zh' ? '客戶管理' : 'Customer Management'}</div>
          <h1>{t('csc.title')}</h1>
          <div className="page-header__sub">{t('csc.sub')}</div>
        </div>
      </div>

      {/* Stat summary bar */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 20 }}>
        {statCards.map(s => (
          <Card key={s.label} style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: `${s.color}14`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <Icon name={s.icon} size={18} style={{ color: s.color }} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--mai-fg)', lineHeight: 1 }}>{s.value}</div>
              <div style={{ fontSize: 11.5, color: 'var(--mai-fg-3)', marginTop: 3 }}>{s.label}</div>
            </div>
          </Card>
        ))}
      </div>

      {/* Tab bar */}
      <div className="table-toolbar" style={{ background: 'white', border: '1px solid var(--mai-border)', borderRadius: 12, marginBottom: 20 }}>
        <div className="table-toolbar__filters">
          {CSC_TABS.map(x => (
            <button key={x.id} className={`filter-chip ${tab === x.id ? 'is-active' : ''}`} onClick={() => setTab(x.id)}>
              {t(x.key)}<span className="filter-chip__count">{counts[x.id]}</span>
            </button>
          ))}
        </div>
      </div>

      {/* ── Tab: 授權總覽 ── */}
      {tab === 'licenses' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(300px,1fr))', gap: 16 }}>
          {CUSTOMER_LICENSES.map(cl => (
            <CscLicenseCard key={cl.id} cl={cl} lang={lang} t={t} />
          ))}
        </div>
      )}

      {/* ── Tab: 到期提醒 ── */}
      {tab === 'renewals' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {urgentGroup.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#EF4444' }} />
                <span style={{ fontSize: 11.5, fontWeight: 700, color: '#DC2626', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {t('csc.section.immediate')}
                </span>
              </div>
              <Card style={{ padding: 0, overflow: 'hidden' }}>
                {urgentGroup.map(cl => <CscRenewalRow key={cl.id} cl={cl} lang={lang} t={t} />)}
              </Card>
            </div>
          )}
          {soonGroup.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#6366F1' }} />
                <span style={{ fontSize: 11.5, fontWeight: 700, color: '#6366F1', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {t('csc.section.soon')}
                </span>
              </div>
              <Card style={{ padding: 0, overflow: 'hidden' }}>
                {soonGroup.map(cl => <CscRenewalRow key={cl.id} cl={cl} lang={lang} t={t} />)}
              </Card>
            </div>
          )}
          {safeGroup.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#26C281' }} />
                <span style={{ fontSize: 11.5, fontWeight: 700, color: '#059669', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {t('csc.section.safe')}
                </span>
              </div>
              <Card style={{ padding: 0, overflow: 'hidden' }}>
                {safeGroup.map(cl => <CscRenewalRow key={cl.id} cl={cl} lang={lang} t={t} />)}
              </Card>
            </div>
          )}
          {urgentGroup.length === 0 && soonGroup.length === 0 && safeGroup.length === 0 && (
            <div className="empty"><Icon name="check-circle" /><div>{lang === 'zh' ? '目前沒有需要跟進的授權' : 'No renewals to follow up'}</div></div>
          )}
        </div>
      )}

      {/* ── Tab: 使用量警示 ── */}
      {tab === 'alerts' && (
        alertsList.length > 0 ? (
          <Card style={{ padding: 0, overflow: 'hidden' }}>
            {alertsList.map(cl => <CscAlertRow key={cl.id} cl={cl} lang={lang} t={t} />)}
          </Card>
        ) : (
          <div className="empty">
            <Icon name="check-circle" />
            <div>{lang === 'zh' ? '目前沒有使用量異常警示' : 'No usage alerts at this time'}</div>
          </div>
        )
      )}
    </div>
  );
};

window.CustomerSuccessPage = CustomerSuccessPage;
