// assistant-artifact.jsx — safe mobile artifact renderer

const ARTIFACT_COLORS = typeof TABI_COLORS !== 'undefined' ? TABI_COLORS : {
  ink: '#18140F',
  ink2: '#574B40',
  ink3: '#8D8071',
  bg: '#F7F0E5',
  bg2: '#EEE2D3',
  card: '#FFFAF2',
  line: 'rgba(24,20,15,0.10)',
  line2: 'rgba(24,20,15,0.16)',
  red: '#B94A35',
  redDeep: '#8F3728',
  green: '#55705A',
  blue: '#365A77',
  warn: '#BE8A35',
  gold: '#D8B66B',
  shadowSoft: '0 8px 22px rgba(55,42,31,0.08)',
};
const ARTIFACT_SERIF = typeof tabiSerif !== 'undefined'
  ? tabiSerif
  : `"Noto Serif JP","Shippori Mincho","Hiragino Mincho ProN",serif`;

function AssistantArtifactScreen({ go, artifactId }) {
  const [artifact, setArtifact] = React.useState(null);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!artifactId) {
      setError('找不到報告 ID');
      setLoading(false);
      return;
    }
    setLoading(true);
    fetch(`/api/assistant/artifacts/${artifactId}`, {
      headers: { Authorization: `Bearer ${window.tabiToken()}` },
    })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('讀取報告失敗')))
      .then(data => {
        setArtifact(data);
        setError('');
      })
      .catch(e => setError(e.message || '讀取報告失敗'))
      .finally(() => setLoading(false));
  }, [artifactId]);

  const content = artifact?.content || {};
  const money = (amount, currency = content.metrics?.currency) => {
    if (currency === 'JPY') return `¥${Number(amount || 0).toLocaleString()}`;
    if (currency === 'TWD') return `NT$${Number(amount || 0).toLocaleString()}`;
    return `${currency || ''} ${Number(amount || 0).toLocaleString()}`.trim();
  };
  const moneyList = (rows, fallbackAmount, fallbackCurrency) => {
    if (Array.isArray(rows) && rows.length) return rows.map(row => money(row.amount, row.currency)).join(' / ');
    return money(fallbackAmount, fallbackCurrency);
  };
  const rangeText = {
    all: '整趟旅程',
    today: '今日',
    yesterday: '昨日',
    last_7_days: '最近 7 天',
  }[content.date_range] || '自訂範圍';

  const PageHeader = () => (
    <div style={{
      position: 'sticky', top: 0, zIndex: 20,
      padding: 'calc(env(safe-area-inset-top, 0px) + 12px) 14px 12px',
      background: 'rgba(247,240,229,0.86)',
      backdropFilter: 'blur(18px)',
      WebkitBackdropFilter: 'blur(18px)',
      borderBottom: `1px solid ${ARTIFACT_COLORS.line}`,
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <button onClick={() => {
        if (history.length > 1) history.back();
        else if (go) go('home');
        else location.href = '/';
      }} style={{
        width: 40, height: 40, borderRadius: 15,
        border: `1px solid ${ARTIFACT_COLORS.line}`,
        background: ARTIFACT_COLORS.card,
        color: ARTIFACT_COLORS.ink,
        fontSize: 22,
        cursor: 'pointer',
      }}>‹</button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10.5, fontWeight: 950, color: ARTIFACT_COLORS.red, letterSpacing: '0.12em' }}>AI ARTIFACT</div>
        <div style={{
          marginTop: 2,
          fontFamily: ARTIFACT_SERIF,
          fontSize: 19,
          fontWeight: 850,
          color: ARTIFACT_COLORS.ink,
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>{content.title || artifact?.title || '旅程支出報告'}</div>
      </div>
    </div>
  );

  const MetricGrid = () => {
    const metrics = content.metrics || {};
    const items = [
      ['總支出', moneyList(metrics.total_by_currency, metrics.total, metrics.currency)],
      ['我的合計', moneyList(metrics.my_by_currency, metrics.my_total, metrics.currency)],
      ['個人', moneyList(metrics.personal_by_currency, metrics.personal_total, metrics.currency)],
      ['共同', moneyList(metrics.shared_by_currency, metrics.shared_total, metrics.currency)],
    ];
    return (
      <section style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9 }}>
        {items.map(([label, value]) => (
          <div key={label} style={{
            minHeight: 88,
            borderRadius: 16,
            padding: 13,
            background: ARTIFACT_COLORS.card,
            border: `1px solid ${ARTIFACT_COLORS.line}`,
            boxShadow: '0 10px 24px rgba(55,42,31,0.06)',
          }}>
            <div style={{ fontSize: 11.5, color: ARTIFACT_COLORS.ink3, fontWeight: 900 }}>{label}</div>
            <div style={{ marginTop: 10, fontSize: value.length > 14 ? 16 : 20, lineHeight: 1.25, color: ARTIFACT_COLORS.ink, fontWeight: 950 }}>{value}</div>
          </div>
        ))}
      </section>
    );
  };

  const BarSection = ({ title, data }) => {
    const rows = (data || []).filter(d => Number(d.amount || 0) > 0).slice(0, 7);
    const max = Math.max(1, ...rows.map(d => d.amount || 0));
    return (
      <section style={sectionStyle}>
        <SectionTitle title={title} />
        {rows.length === 0 ? <EmptyLine /> : rows.map(row => (
          <div key={row.name} style={{ marginTop: 11 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 12.5, fontWeight: 850 }}>
              <span style={{ color: ARTIFACT_COLORS.ink2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.label || row.name}</span>
              <span style={{ color: ARTIFACT_COLORS.ink }}>{money(row.amount, row.currency)}</span>
            </div>
            <div style={{ marginTop: 6, height: 10, borderRadius: 999, background: 'rgba(24,20,15,0.07)', overflow: 'hidden' }}>
              <div style={{ width: `${Math.max(4, (row.amount / max) * 100)}%`, height: '100%', borderRadius: 999, background: ARTIFACT_COLORS.red }} />
            </div>
          </div>
        ))}
      </section>
    );
  };

  const DonutSection = () => {
    const data = content.series?.visibility || [];
    const usable = data.filter(row => row.currency === (content.metrics?.currency || row.currency));
    const total = usable.reduce((sum, row) => sum + Number(row.amount || 0), 0);
    const personal = usable.find(row => row.name === '個人')?.amount || 0;
    const pct = total ? Math.round((personal / total) * 100) : 0;
    return (
      <section style={sectionStyle}>
        <SectionTitle title="個人 / 共同比例" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginTop: 12 }}>
          <div style={{
            width: 106, height: 106, borderRadius: '50%',
            background: `conic-gradient(${ARTIFACT_COLORS.red} 0 ${pct}%, ${ARTIFACT_COLORS.blue} ${pct}% 100%)`,
            display: 'grid', placeItems: 'center',
            boxShadow: 'inset 0 0 0 14px rgba(255,250,242,0.92)',
          }}>
            <div style={{ fontSize: 17, fontWeight: 950, color: ARTIFACT_COLORS.ink }}>{pct}%</div>
          </div>
          <div style={{ flex: 1, display: 'grid', gap: 9 }}>
            {data.map((row, idx) => (
              <div key={`${row.name}-${row.currency}-${idx}`} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: 850 }}>
                <span style={{ color: ARTIFACT_COLORS.ink2 }}>{row.label || row.name}</span>
                <span style={{ color: ARTIFACT_COLORS.ink }}>{money(row.amount, row.currency)}</span>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  };

  const LineSection = () => {
    const data = content.series?.daily || [];
    const W = 320, H = 130, pad = 16;
    const max = Math.max(1, ...data.map(d => d.amount || 0));
    const points = data.map((d, i) => {
      const x = data.length <= 1 ? W / 2 : pad + i * ((W - pad * 2) / (data.length - 1));
      const y = H - pad - ((d.amount || 0) / max) * (H - pad * 2);
      return [x, y];
    });
    const path = points.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
    return (
      <section style={sectionStyle}>
        <SectionTitle title="每日支出趨勢" />
        {data.length === 0 ? <EmptyLine /> : data.length === 1 ? (
          <div style={{
            marginTop: 12,
            borderRadius: 16,
            padding: 14,
            background: ARTIFACT_COLORS.bg,
            border: `1px solid ${ARTIFACT_COLORS.line}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 12,
          }}>
            <div>
              <div style={{ fontSize: 11.5, color: ARTIFACT_COLORS.ink3, fontWeight: 900 }}>單日資料</div>
              <div style={{ marginTop: 5, fontSize: 15, color: ARTIFACT_COLORS.ink, fontWeight: 950 }}>{data[0].date}</div>
            </div>
            <div style={{ fontSize: 20, color: ARTIFACT_COLORS.red, fontWeight: 950 }}>{money(data[0].amount, data[0].currency)}</div>
          </div>
        ) : (
          <>
            <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="150" preserveAspectRatio="none" style={{ marginTop: 8, display: 'block' }}>
              <path d={`M${pad} ${H - pad} H${W - pad}`} stroke="rgba(24,20,15,0.12)" strokeWidth="1" />
              <path d={path} fill="none" stroke={ARTIFACT_COLORS.red} strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
              {points.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="4" fill={ARTIFACT_COLORS.card} stroke={ARTIFACT_COLORS.red} strokeWidth="3" />)}
            </svg>
            <div style={{ display: 'flex', justifyContent: 'space-between', color: ARTIFACT_COLORS.ink3, fontSize: 10.5, fontWeight: 800 }}>
              <span>{data[0]?.date || ''}</span>
              <span>{data[data.length - 1]?.date || ''}</span>
            </div>
          </>
        )}
      </section>
    );
  };

  const ExpenseTable = () => {
    const rows = content.rows || [];
    return (
      <section style={sectionStyle}>
        <SectionTitle title="支出明細" />
        {rows.length === 0 ? <EmptyLine /> : rows.map(row => (
          <div key={row.id} style={{
            display: 'grid',
            gridTemplateColumns: '1fr auto',
            gap: 8,
            padding: '11px 0',
            borderBottom: `1px solid ${ARTIFACT_COLORS.line}`,
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13.5, color: ARTIFACT_COLORS.ink, fontWeight: 900, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.title}</div>
              <div style={{ marginTop: 3, fontSize: 11.5, color: ARTIFACT_COLORS.ink3, fontWeight: 750 }}>{row.date} · {row.category} · {row.visibility === 'shared' ? '共同' : '個人'}</div>
            </div>
            <div style={{ color: ARTIFACT_COLORS.ink, fontWeight: 950 }}>{money(row.amount, row.currency)}</div>
          </div>
        ))}
      </section>
    );
  };

  const Insight = () => (
    <section style={{
      ...sectionStyle,
      background: 'linear-gradient(180deg, rgba(24,20,15,0.96), rgba(50,39,30,0.96))',
      color: '#FFFAF2',
      border: '1px solid rgba(255,250,242,0.12)',
    }}>
      <div style={{ fontSize: 10.5, letterSpacing: '0.12em', color: 'rgba(255,250,242,0.56)', fontWeight: 950 }}>AI INSIGHT</div>
      <div style={{ marginTop: 9, fontSize: 14, lineHeight: 1.75, color: 'rgba(255,250,242,0.86)', fontWeight: 650 }}>
        {content.insight || '目前資料還不多，等支出增加後我可以幫你看趨勢、比例和異常項目。'}
      </div>
    </section>
  );

  const renderSection = (type) => {
    if (typeof type === 'object' && type) {
      if (type.type === 'table') {
        return (
          <section key={type.title} style={sectionStyle}>
            <SectionTitle title={type.title || '明細'} />
            {(type.rows || []).length === 0 ? <EmptyLine /> : (type.rows || []).map((row, idx) => (
              <div key={`${row.label}-${idx}`} style={{
                display: 'grid',
                gridTemplateColumns: '1fr auto',
                gap: 8,
                padding: '11px 0',
                borderBottom: idx === (type.rows || []).length - 1 ? 'none' : `1px solid ${ARTIFACT_COLORS.line}`,
              }}>
                <div style={{ minWidth: 0, fontSize: 13.5, color: ARTIFACT_COLORS.ink, fontWeight: 900, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.label}</div>
                <div style={{ color: ARTIFACT_COLORS.ink2, fontWeight: 850, textAlign: 'right', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.value}</div>
              </div>
            ))}
          </section>
        );
      }
      if (type.type === 'insight') {
        return (
          <section key={type.text || type.title || 'insight'} style={{
            ...sectionStyle,
            background: 'linear-gradient(180deg, rgba(24,20,15,0.96), rgba(50,39,30,0.96))',
            color: '#FFFAF2',
            border: '1px solid rgba(255,250,242,0.12)',
          }}>
            <div style={{ fontSize: 10.5, letterSpacing: '0.12em', color: 'rgba(255,250,242,0.56)', fontWeight: 950 }}>AI INSIGHT</div>
            <div style={{ marginTop: 9, fontSize: 14, lineHeight: 1.75, color: 'rgba(255,250,242,0.86)', fontWeight: 650 }}>{type.text}</div>
          </section>
        );
      }
      return null;
    }
    if (type === 'metric_grid') return <MetricGrid key={type} />;
    if (type === 'daily_line') return <LineSection key={type} />;
    if (type === 'category_bar') return <BarSection key={type} title="分類支出" data={content.series?.categories} />;
    if (type === 'member_bar') return <BarSection key={type} title="付款人排行" data={content.series?.payers} />;
    if (type === 'visibility_donut') return <DonutSection key={type} />;
    if (type === 'expense_table') return <ExpenseTable key={type} />;
    if (type === 'insight') return <Insight key={type} />;
    return null;
  };

  return (
    <div style={{ minHeight: '100%', background: ARTIFACT_COLORS.bg, paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 24px)' }}>
      <PageHeader />
      {loading && <div style={{ padding: 18, color: ARTIFACT_COLORS.ink3, fontWeight: 800 }}>讀取報告中...</div>}
      {error && <div style={{ padding: 18, color: ARTIFACT_COLORS.red, fontWeight: 850 }}>{error}</div>}
      {!loading && !error && (
        <main style={{ padding: 14, display: 'grid', gap: 12 }}>
          <section style={{
            borderRadius: 24,
            padding: 18,
            background: 'linear-gradient(145deg, #18140F, #4B2D22)',
            color: '#fff',
            boxShadow: '0 22px 48px rgba(55,42,31,0.18)',
            overflow: 'hidden',
          }}>
            <div style={{ fontSize: 11, fontWeight: 950, color: 'rgba(255,250,242,0.58)', letterSpacing: '0.14em' }}>TRIP EXPENSE REPORT</div>
            <h1 style={{ margin: '8px 0 0', fontFamily: ARTIFACT_SERIF, fontSize: 28, lineHeight: 1.12, color: '#FFFAF2' }}>{content.title || artifact?.title}</h1>
            <div style={{ marginTop: 9, fontSize: 13, color: 'rgba(255,250,242,0.70)', lineHeight: 1.6 }}>
              {content.trip?.name || '旅程'} · {rangeText} · {content.metrics?.expense_count || 0} 筆
            </div>
          </section>
          {(content.sections || ['metric_grid']).map(renderSection)}
        </main>
      )}
    </div>
  );
}

const sectionStyle = {
  borderRadius: 18,
  padding: 14,
  background: ARTIFACT_COLORS.card,
  border: `1px solid ${ARTIFACT_COLORS.line}`,
  boxShadow: '0 10px 24px rgba(55,42,31,0.06)',
};

function SectionTitle({ title }) {
  return <div style={{ fontFamily: ARTIFACT_SERIF, fontSize: 18, fontWeight: 850, color: ARTIFACT_COLORS.ink }}>{title}</div>;
}

function EmptyLine() {
  return <div style={{ marginTop: 10, fontSize: 12.5, color: ARTIFACT_COLORS.ink3, fontWeight: 750 }}>這個範圍目前沒有可顯示的資料。</div>;
}
