(function(){
// 交易日誌（v8 Phase 6，2026-05-08）
// 接線：GET/POST/DELETE /api/trade-log（D1 trade_log 表）

const T = window.STOCK_TOKENS;

const ACTION_LABEL = {
  buy: '買進',
  sell: '賣出',
  add: '加碼',
  reduce: '減碼',
};
const ACTION_COLOR = {
  buy: { bg: 'oklch(0.96 0.05 25)', text: 'oklch(0.45 0.20 25)' },
  add: { bg: 'oklch(0.96 0.05 25)', text: 'oklch(0.45 0.20 25)' },
  sell: { bg: 'oklch(0.96 0.04 155)', text: 'oklch(0.40 0.15 155)' },
  reduce: { bg: 'oklch(0.96 0.04 155)', text: 'oklch(0.40 0.15 155)' },
};

function NewTradeForm({ onSave, onCancel }) {
  const today = new Date().toISOString().slice(0, 10);
  const [form, setForm] = React.useState({
    trade_date: today,
    code: '',
    name: '',
    action: 'buy',
    shares: '',
    price: '',
    reason: '',
    reflection: '',
    emotion: 3,
    system_advice: '',
    followed_advice: 1,
  });
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState('');

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async () => {
    if (!form.code || !form.shares || !form.price) {
      setErr('代號、張數、價格為必填');
      return;
    }
    setSaving(true);
    setErr('');
    try {
      const body = {
        ...form,
        shares: Number(form.shares),
        price: Number(form.price),
        emotion: Number(form.emotion),
        followed_advice: Number(form.followed_advice),
      };
      await window.fetchAPI('/api/trade-log', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      onSave();
    } catch (e) {
      setErr(e.message || '儲存失敗');
    } finally {
      setSaving(false);
    }
  };

  const inputStyle = {
    width: '100%', padding: '6px 10px', fontSize: 12,
    border: '1px solid ' + T.border, borderRadius: 4,
    fontFamily: T.fontSans, boxSizing: 'border-box',
  };
  const labelStyle = { fontSize: 11, fontWeight: 600, color: T.text2, marginBottom: 4, display: 'block' };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
      zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center',
    }} onClick={(e) => { if (e.target === e.currentTarget) onCancel(); }}>
      <div style={{
        width: '90%', maxWidth: 520, maxHeight: '88vh', overflowY: 'auto',
        background: T.bg, borderRadius: 8, padding: 24,
        boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
      }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: T.text, marginBottom: 16 }}>
          📝 新增交易紀錄
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={labelStyle}>交易日期 *</label>
            <input type="date" value={form.trade_date} onChange={e => set('trade_date', e.target.value)} style={inputStyle} />
          </div>
          <div>
            <label style={labelStyle}>動作 *</label>
            <select value={form.action} onChange={e => set('action', e.target.value)} style={inputStyle}>
              <option value="buy">買進</option>
              <option value="add">加碼</option>
              <option value="sell">賣出</option>
              <option value="reduce">減碼</option>
            </select>
          </div>
          <div>
            <label style={labelStyle}>代號 *</label>
            <input value={form.code} onChange={e => set('code', e.target.value.trim())} style={inputStyle} placeholder="2330" />
          </div>
          <div>
            <label style={labelStyle}>名稱</label>
            <input value={form.name} onChange={e => set('name', e.target.value)} style={inputStyle} placeholder="台積電" />
          </div>
          <div>
            <label style={labelStyle}>張數 *</label>
            <input type="number" value={form.shares} onChange={e => set('shares', e.target.value)} style={inputStyle} placeholder="1" min="1" />
          </div>
          <div>
            <label style={labelStyle}>成交均價 *</label>
            <input type="number" step="0.05" value={form.price} onChange={e => set('price', e.target.value)} style={inputStyle} placeholder="195.00" />
          </div>
          <div style={{ gridColumn: '1 / 3' }}>
            <label style={labelStyle}>進出理由</label>
            <textarea value={form.reason} onChange={e => set('reason', e.target.value)} style={{ ...inputStyle, minHeight: 60 }} placeholder="為何在此時做這筆交易？" />
          </div>
          <div style={{ gridColumn: '1 / 3' }}>
            <label style={labelStyle}>事後心得（成交後再回填）</label>
            <textarea value={form.reflection} onChange={e => set('reflection', e.target.value)} style={{ ...inputStyle, minHeight: 50 }} placeholder="事後檢視這筆交易學到什麼" />
          </div>
          <div>
            <label style={labelStyle}>情緒（1=慌張 / 5=從容）</label>
            <input type="range" min="1" max="5" value={form.emotion} onChange={e => set('emotion', e.target.value)} style={{ width: '100%' }} />
            <div style={{ textAlign: 'center', fontSize: 12, fontFamily: T.fontMono, color: T.text2 }}>{form.emotion}</div>
          </div>
          <div>
            <label style={labelStyle}>遵守系統建議？</label>
            <select value={form.followed_advice} onChange={e => set('followed_advice', e.target.value)} style={inputStyle}>
              <option value="1">是</option>
              <option value="0">否（有自己的判斷）</option>
            </select>
          </div>
          <div style={{ gridColumn: '1 / 3' }}>
            <label style={labelStyle}>當下系統建議（可從健診卡複製）</label>
            <input value={form.system_advice} onChange={e => set('system_advice', e.target.value)} style={inputStyle} placeholder="例：續抱（健康度 82）" />
          </div>
        </div>
        {err && <div style={{ marginTop: 12, padding: 10, background: 'oklch(0.95 0.05 25)', color: 'oklch(0.45 0.20 25)', borderRadius: 4, fontSize: 12 }}>{err}</div>}
        <div style={{ display: 'flex', gap: 8, marginTop: 16, justifyContent: 'flex-end' }}>
          <button onClick={onCancel} style={{
            padding: '8px 16px', background: T.surface, border: '1px solid ' + T.border,
            borderRadius: 4, fontSize: 12, cursor: 'pointer', color: T.text,
          }}>取消</button>
          <button onClick={handleSubmit} disabled={saving} style={{
            padding: '8px 16px', background: T.primary || 'oklch(0.55 0.18 240)', color: 'white',
            border: 'none', borderRadius: 4, fontSize: 12, cursor: saving ? 'wait' : 'pointer',
            fontWeight: 600,
          }}>{saving ? '儲存中...' : '💾 儲存'}</button>
        </div>
      </div>
    </div>
  );
}

function TradeLogPage() {
  const vp = window.useViewport();
  const [data, setData] = React.useState({ items: [], stats: null });
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [showForm, setShowForm] = React.useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const result = await window.fetchAPI('/api/trade-log');
      setData(result);
      setErr('');
    } catch (e) {
      setErr(e.message || '載入失敗');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => { load(); }, []);

  const handleDelete = async (id) => {
    if (!confirm('確定刪除這筆紀錄？')) return;
    try {
      await window.fetchAPI('/api/trade-log?id=' + id, { method: 'DELETE' });
      await load();
    } catch (e) {
      alert('刪除失敗：' + e.message);
    }
  };

  const pad = vp.isMobile ? 12 : 24;

  return (
    <div style={{ padding: pad, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 18, fontWeight: 700, color: T.text }}>📓 個人交易日誌</div>
          <div style={{ fontSize: 11, color: T.text3, marginTop: 4 }}>
            盤後檢討用 — 紀錄每筆下單原因 + 心得 + 是否遵循系統建議
          </div>
        </div>
        <button onClick={() => setShowForm(true)} style={{
          padding: '8px 16px', background: T.primary || 'oklch(0.55 0.18 240)', color: 'white',
          border: 'none', borderRadius: 4, fontSize: 12, cursor: 'pointer', fontWeight: 600,
        }}>＋ 新增紀錄</button>
      </div>

      {/* 統計 */}
      {data.stats && (
        <div style={{
          display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 12,
        }}>
          <div style={{ background: T.surface, padding: 14, borderRadius: 6, border: '1px solid ' + T.border }}>
            <div style={{ fontSize: 11, color: T.text3 }}>總交易次數</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: T.text, fontFamily: T.fontMono }}>{data.stats.total}</div>
          </div>
          <div style={{ background: T.surface, padding: 14, borderRadius: 6, border: '1px solid ' + T.border }}>
            <div style={{ fontSize: 11, color: T.text3 }}>遵守系統建議</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: T.text, fontFamily: T.fontMono }}>{data.stats.followed_count}</div>
          </div>
          <div style={{ background: T.surface, padding: 14, borderRadius: 6, border: '1px solid ' + T.border }}>
            <div style={{ fontSize: 11, color: T.text3 }}>遵守率</div>
            <div style={{ fontSize: 22, fontWeight: 700, color: T.text, fontFamily: T.fontMono }}>
              {data.stats.follow_rate_pct}%
            </div>
          </div>
        </div>
      )}

      {/* 表格 */}
      {loading ? (
        <div style={{ padding: 40, textAlign: 'center', color: T.text3 }}>載入中...</div>
      ) : err ? (
        <div style={{ padding: 16, background: 'oklch(0.95 0.05 25)', color: 'oklch(0.45 0.20 25)', borderRadius: 6 }}>
          錯誤：{err}<br/>
          <small style={{ color: T.text3 }}>若是 trade_log 表還沒建，請到 D1 Console 跑 web/schema.sql</small>
        </div>
      ) : data.items.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: T.text3, fontSize: 13 }}>
          尚無交易紀錄。點右上角「＋ 新增紀錄」開始建立日誌。
        </div>
      ) : (
        <div style={{ background: T.surface, borderRadius: 6, border: '1px solid ' + T.border, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ background: T.hover, color: T.text3, fontSize: 10, textAlign: 'left' }}>
                <th style={{ padding: 10, fontWeight: 600 }}>日期</th>
                <th style={{ padding: 10, fontWeight: 600 }}>代號</th>
                <th style={{ padding: 10, fontWeight: 600 }}>動作</th>
                <th style={{ padding: 10, fontWeight: 600, textAlign: 'right' }}>張數</th>
                <th style={{ padding: 10, fontWeight: 600, textAlign: 'right' }}>價格</th>
                {!vp.isMobile && <th style={{ padding: 10, fontWeight: 600 }}>理由</th>}
                <th style={{ padding: 10, fontWeight: 600, textAlign: 'center' }}>遵</th>
                <th style={{ padding: 10, fontWeight: 600, textAlign: 'center' }}></th>
              </tr>
            </thead>
            <tbody>
              {data.items.map(it => {
                const ac = ACTION_COLOR[it.action] || ACTION_COLOR.buy;
                return (
                  <tr key={it.id} style={{ borderTop: '1px solid ' + T.border }}>
                    <td style={{ padding: 10, fontFamily: T.fontMono, fontSize: 11, color: T.text2 }}>{it.trade_date}</td>
                    <td style={{ padding: 10, fontFamily: T.fontMono }}>{it.code}<br/><span style={{ fontSize: 10, color: T.text3 }}>{it.name}</span></td>
                    <td style={{ padding: 10 }}>
                      <span style={{
                        padding: '2px 8px', borderRadius: 3, fontSize: 10, fontWeight: 700,
                        background: ac.bg, color: ac.text,
                      }}>{ACTION_LABEL[it.action] || it.action}</span>
                    </td>
                    <td style={{ padding: 10, fontFamily: T.fontMono, textAlign: 'right' }}>{it.shares}</td>
                    <td style={{ padding: 10, fontFamily: T.fontMono, textAlign: 'right' }}>{Number(it.price).toFixed(2)}</td>
                    {!vp.isMobile && (
                      <td style={{ padding: 10, color: T.text2, fontSize: 11, maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={it.reason}>
                        {it.reason || '—'}
                      </td>
                    )}
                    <td style={{ padding: 10, textAlign: 'center' }}>
                      {it.followed_advice === 1 ? '✓' : it.followed_advice === 0 ? '✗' : '—'}
                    </td>
                    <td style={{ padding: 10, textAlign: 'center' }}>
                      <button onClick={() => handleDelete(it.id)} style={{
                        padding: '2px 6px', background: 'transparent', border: '1px solid ' + T.border,
                        borderRadius: 3, fontSize: 10, cursor: 'pointer', color: T.text3,
                      }}>刪</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {showForm && <NewTradeForm onSave={() => { setShowForm(false); load(); }} onCancel={() => setShowForm(false)} />}
    </div>
  );
}

window.TradeLogPage = TradeLogPage;
})();
