import { useState, useRef, useCallback } from "react";

const SYSTEM_PROMPT = `You are the Oracle forward test analyst for Oracle v1.6.1 — a Pine Script NQ/MNQ futures strategy. You receive a Strategy Tester CSV export and produce a structured session debrief.

The CSV columns are: Trade #, Type, Date and time, Signal, Price USD, Position size (qty), Position size (value), Net P&L USD, Net P&L %, Favorable excursion USD, Favorable excursion %, Adverse excursion USD, Adverse excursion %, Cumulative P&L USD, Cumulative P&L %

Each trade has two rows: Entry and Exit. Match them by Trade #. Direction = "Entry long" or "Entry short". Net P&L is on the Exit row. MAE = Adverse excursion USD (how far it went against). MFE = Favorable excursion USD (how far it went in favour before exit).

The v1.6.1 forward test tracks these OPEN QUESTIONS for v1.7 resolution:
1. Does the Asian High hold as a TP target on normal days?
2. Does Oracle's signal logic qualify cleanly at Asian levels?
3. Is the 60pt minAsianRangePts threshold correct?
4. Does the Asian Midpoint act as a reliable level?
5. Does adding Asian TP targets affect win rate vs profit factor?
6. Near-miss retest: when Touch 2 enters ±8pt zone but stops short of exact level — entry fires under current logic. Log any instances where this may have occurred.

Exit types from Signal column:
- "⏱ Max duration" = duration timer — flagged as a concern since v1.6.1 removes this
- "Short Exit" / "Long Exit" = structural TP or SL hit
- "🎯 Daily profit target" = daily limit
- "🛑 Daily loss limit" = daily limit

Respond ONLY with a JSON object. No preamble, no markdown, no backticks. Exact structure:

{
  "session_date": "YYYY-MM-DD",
  "week": "W1/W2/W3/W4",
  "total_trades": 0,
  "winners": 0,
  "losers": 0,
  "win_rate": 0.0,
  "net_pnl": 0.0,
  "profit_factor": 0.0,
  "avg_win": 0.0,
  "avg_loss": 0.0,
  "avg_mae": 0.0,
  "avg_mfe": 0.0,
  "largest_win": 0.0,
  "largest_loss": 0.0,
  "max_consec_losses": 0,
  "daily_target_hit": false,
  "daily_loss_hit": false,
  "duration_timer_exits": 0,
  "contracts": 0,
  "directions": { "long": 0, "short": 0 },
  "headline": "One sentence — the single most important thing about this session.",
  "performance_summary": "2-3 sentences covering P&L, win rate, and any standout trades. Be specific with numbers.",
  "asian_level_observations": "What did this session tell us about Asian level behaviour? If no Asian levels triggered, say so explicitly. Note any instances where price approached Asian High or Low and what happened.",
  "signal_quality": "Which signal types fired? Were any duration timer exits present (flag as concern)? Any signals that looked weak or strong?",
  "open_questions_update": "For each of the 6 v1.7 open questions, one sentence on what this session's data adds. If no data point, say 'No data this session'.",
  "anomalies": "List any unexpected behaviours — signals on disabled days, wrong session, unusual MAE, etc. If none, say 'None observed'.",
  "tracker_update": "Exact text to paste into the Forward Test Log row for this session in the Development Tracker. Format: Date | Trades | P&L | Win Rate | Key observation",
  "flags": []
}

flags is an array of strings — each a short alert worth highlighting, e.g. "Duration timer exit on Trade 1 — review for v1.6.1 removal". Empty array if none.`;

const DEMO_CSV = `Trade #,Type,Date and time,Signal,Price USD,Position size (qty),Position size (value),Net P&L USD,Net P&L %,Favorable excursion USD,Favorable excursion %,Adverse excursion USD,Adverse excursion %,Cumulative P&L USD,Cumulative P&L %
1,Exit short,2026-03-30 12:15,⏱ Max duration (90m) — closing trade,23334.75,4,186192,-490,-0.26,26,0.01,-1312,-0.70,-490,-0.05
1,Entry short,2026-03-30 10:45,Short,23274,4,186192,-490,-0.26,26,0.01,-1312,-0.70,-490,-0.05
2,Exit short,2026-03-30 13:10,Short Exit,23246.75,4,186110,132,0.07,154,0.08,-260,-0.14,-358,-0.04
2,Entry short,2026-03-30 13:05,Short,23263.75,4,186110,132,0.07,154,0.08,-260,-0.14,-358,-0.04
3,Exit short,2026-03-31 03:15,Short Exit,23245.75,4,186124,154,0.08,156,0.08,-104,-0.06,-204,-0.02
3,Entry short,2026-03-31 03:15,Short,23265.5,4,186124,154,0.08,156,0.08,-104,-0.06,-204,-0.02
5,Exit long,2026-03-31 10:30,Long Exit,23586,4,188618,66,0.03,88,0.05,-658,-0.35,-68,-0.01
5,Entry long,2026-03-31 10:00,Long,23577.25,4,188618,66,0.03,88,0.05,-658,-0.35,-68,-0.01
7,Exit long,2026-04-02 10:00,Long Exit,23917.75,4,191182,156,0.08,158,0.08,-2,0.00,242,0.02
7,Entry long,2026-04-02 10:00,Long,23897.75,4,191182,156,0.08,158,0.08,-2,0.00,242,0.02`;

const C = {
  bg: "#060910", surface: "#0A0E1A", surface2: "#0F1628",
  border: "#1E2A40", border2: "#2A3550",
  teal: "#1CB8A0", tealDim: "#0A2018", tealBorder: "#0D3025",
  red: "#EF5350", redDim: "#1A0808", redBorder: "#2A0A0A",
  gold: "#E8B47B", amber: "#BA7517", amberDim: "#1A1204",
  cyan: "#00BCD4", cyanDim: "#041418",
  silver: "#8A9BB8", muted: "#3A4560",
  white: "#D1D5E0",
};

const s = {
  root: { background: C.bg, borderRadius: 10, border: `1px solid ${C.border}`, fontFamily: "'Space Mono', monospace, sans-serif", color: C.white, overflow: "hidden" },
  topbar: { background: C.surface, borderBottom: `1px solid ${C.border}`, padding: "8px 14px", display: "flex", alignItems: "center", justifyContent: "space-between" },
  logo: { color: C.gold, fontSize: 13, fontWeight: 700, letterSpacing: "0.08em" },
  tag: { background: C.surface2, border: `1px solid ${C.border2}`, color: C.silver, fontSize: 8, padding: "2px 7px", borderRadius: 3, marginLeft: 8 },
  body: { padding: "14px 16px" },
  sectionLabel: { fontSize: 8, color: C.muted, letterSpacing: "0.1em", marginBottom: 8 },
  dropzone: { border: `1.5px dashed ${C.border2}`, borderRadius: 8, padding: "28px 20px", textAlign: "center", cursor: "pointer", background: C.surface, transition: "border-color 0.15s" },
  dropzoneActive: { border: `1.5px dashed ${C.teal}`, background: C.tealDim },
  textarea: { width: "100%", background: C.surface2, border: `1px solid ${C.border2}`, color: C.white, borderRadius: 6, padding: "10px 12px", fontSize: 9, fontFamily: "monospace", resize: "vertical", minHeight: 90, outline: "none" },
  btn: { background: C.tealDim, border: `1px solid ${C.tealBorder}`, color: C.teal, padding: "8px 18px", borderRadius: 6, cursor: "pointer", fontSize: 9, fontWeight: 700, letterSpacing: "0.06em", fontFamily: "monospace" },
  btnDisabled: { background: C.surface2, border: `1px solid ${C.border}`, color: C.muted, padding: "8px 18px", borderRadius: 6, cursor: "not-allowed", fontSize: 9, letterSpacing: "0.06em", fontFamily: "monospace" },
  btnGhost: { background: "transparent", border: `1px solid ${C.border2}`, color: C.silver, padding: "5px 12px", borderRadius: 5, cursor: "pointer", fontSize: 8, fontFamily: "monospace" },
  metricCard: { background: C.surface2, border: `1px solid ${C.border}`, borderRadius: 6, padding: "10px 12px", flex: 1, minWidth: 0 },
  metricLabel: { fontSize: 7, color: C.muted, letterSpacing: "0.08em", marginBottom: 3 },
  metricVal: { fontSize: 18, fontWeight: 700, fontFamily: "monospace" },
  section: { background: C.surface, border: `1px solid ${C.border}`, borderRadius: 7, padding: "12px 14px", marginBottom: 10 },
  sectionHead: { fontSize: 8, color: C.silver, letterSpacing: "0.1em", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 },
  dot: (col) => ({ width: 5, height: 5, borderRadius: "50%", background: col, flexShrink: 0 }),
  prose: { fontSize: 10, lineHeight: 1.7, color: C.white },
  flag: { background: C.amberDim, border: `1px solid ${C.amber}`, borderRadius: 4, padding: "5px 10px", fontSize: 9, color: "#F5C875", marginBottom: 5 },
  trackerBox: { background: C.surface2, border: `1px solid ${C.border2}`, borderRadius: 5, padding: "8px 12px", fontSize: 9, color: C.teal, fontFamily: "monospace", cursor: "pointer", userSelect: "all" },
  pill: (bg, col, brd) => ({ background: bg, border: `1px solid ${brd}`, color: col, fontSize: 7, padding: "2px 7px", borderRadius: 3, fontFamily: "monospace", fontWeight: 700 }),
};

function MetricCard({ label, value, color }) {
  return (
    <div style={s.metricCard}>
      <div style={s.metricLabel}>{label}</div>
      <div style={{ ...s.metricVal, color: color || C.white }}>{value}</div>
    </div>
  );
}

function SectionBlock({ dotColor, label, children }) {
  return (
    <div style={s.section}>
      <div style={s.sectionHead}>
        <span style={s.dot(dotColor || C.teal)}></span>
        {label}
      </div>
      {children}
    </div>
  );
}

export default function OracleDebrief() {
  const [csv, setCsv] = useState("");
  const [week, setWeek] = useState("W1");
  const [sessionNotes, setSessionNotes] = useState("");
  const [asianRange, setAsianRange] = useState("");
  const [loading, setLoading] = useState(false);
  const [report, setReport] = useState(null);
  const [error, setError] = useState("");
  const [dragging, setDragging] = useState(false);
  const [copied, setCopied] = useState(false);
  const fileRef = useRef();

  const handleFile = useCallback((file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => setCsv(e.target.result);
    reader.readAsText(file);
  }, []);

  const onDrop = useCallback((e) => {
    e.preventDefault();
    setDragging(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }, [handleFile]);

  const runDebrief = async () => {
    if (!csv.trim()) return;
    setLoading(true);
    setError("");
    setReport(null);

    const userMsg = `Oracle v1.6.1 Strategy Tester CSV export — Week ${week}${asianRange ? `. Asian session range today: ${asianRange}pts` : ""}.${sessionNotes ? ` Trader notes: ${sessionNotes}` : ""}

CSV DATA:
${csv.trim()}`;

    try {
      const resp = await fetch("https://api.anthropic.com/v1/messages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          model: "claude-sonnet-4-20250514",
          max_tokens: 1000,
          system: SYSTEM_PROMPT,
          messages: [{ role: "user", content: userMsg }],
        }),
      });
      const data = await resp.json();
      const text = (data.content || []).map(b => b.text || "").join("").trim();
      const clean = text.replace(/^```[a-z]*\n?/, "").replace(/```$/, "").trim();
      const parsed = JSON.parse(clean);
      setReport(parsed);
    } catch (err) {
      setError("Analysis failed — check the CSV format and try again. " + err.message);
    } finally {
      setLoading(false);
    }
  };

  const copyTracker = () => {
    if (!report?.tracker_update) return;
    navigator.clipboard.writeText(report.tracker_update);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const pnlColor = (v) => v > 0 ? C.teal : v < 0 ? C.red : C.silver;
  const fmt$ = (v) => v >= 0 ? `+$${Math.abs(v).toFixed(2)}` : `-$${Math.abs(v).toFixed(2)}`;
  const fmtPct = (v) => `${v.toFixed(1)}%`;

  return (
    <div style={s.root}>
      {/* Topbar */}
      <div style={s.topbar}>
        <div style={{ display: "flex", alignItems: "center" }}>
          <span style={s.logo}>ORACLE</span>
          <span style={s.tag}>v1.6.1</span>
          <span style={s.tag}>SESSION DEBRIEF</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 8, color: C.muted }}>Week</span>
          {["W1","W2","W3","W4"].map(w => (
            <button key={w} onClick={() => setWeek(w)}
              style={{ ...s.btnGhost, ...(week === w ? { borderColor: C.gold, color: C.gold, background: C.amberDim } : {}) }}>
              {w}
            </button>
          ))}
        </div>
      </div>

      <div style={s.body}>
        {!report ? (
          <>
            {/* Drop zone */}
            <div style={s.sectionLabel}>IMPORT CSV</div>
            <div
              style={{ ...s.dropzone, ...(dragging ? s.dropzoneActive : {}) }}
              onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
              onDragLeave={() => setDragging(false)}
              onDrop={onDrop}
              onClick={() => fileRef.current?.click()}
            >
              <input ref={fileRef} type="file" accept=".csv" style={{ display: "none" }}
                onChange={e => handleFile(e.target.files[0])} />
              {csv ? (
                <div>
                  <div style={{ color: C.teal, fontSize: 10, marginBottom: 4 }}>✓ CSV loaded — {csv.split("\n").length - 1} rows</div>
                  <div style={{ fontSize: 8, color: C.muted }}>Click to replace</div>
                </div>
              ) : (
                <div>
                  <div style={{ color: C.silver, fontSize: 10, marginBottom: 4 }}>Drop Strategy Tester CSV here</div>
                  <div style={{ fontSize: 8, color: C.muted }}>or click to browse  ·  .csv files only</div>
                </div>
              )}
            </div>

            {/* Paste alternative */}
            <div style={{ marginTop: 8, marginBottom: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                <span style={{ fontSize: 8, color: C.muted }}>OR PASTE CSV DIRECTLY</span>
                <button style={s.btnGhost} onClick={() => setCsv(DEMO_CSV)}>Load demo (W2 data)</button>
              </div>
              <textarea style={s.textarea} value={csv} onChange={e => setCsv(e.target.value)}
                placeholder="Paste CSV content here..." />
            </div>

            {/* Optional context */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
              <div>
                <div style={{ ...s.sectionLabel, marginBottom: 4 }}>ASIAN RANGE TODAY (pts) — optional</div>
                <input style={{ ...s.textarea, minHeight: "unset", padding: "7px 10px", fontSize: 10 }}
                  value={asianRange} onChange={e => setAsianRange(e.target.value)}
                  placeholder="e.g. 155" />
              </div>
              <div>
                <div style={{ ...s.sectionLabel, marginBottom: 4 }}>TRADER NOTES — optional</div>
                <input style={{ ...s.textarea, minHeight: "unset", padding: "7px 10px", fontSize: 10 }}
                  value={sessionNotes} onChange={e => setSessionNotes(e.target.value)}
                  placeholder="e.g. News event at 08:30, choppy NY session" />
              </div>
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <button
                style={csv.trim() && !loading ? s.btn : s.btnDisabled}
                disabled={!csv.trim() || loading}
                onClick={runDebrief}>
                {loading ? "Analysing..." : "Run Session Debrief →"}
              </button>
              {loading && <span style={{ fontSize: 8, color: C.muted }}>Analysing CSV against v1.6.1 open questions...</span>}
            </div>

            {error && <div style={{ ...s.flag, marginTop: 10 }}>⚠ {error}</div>}
          </>
        ) : (
          <>
            {/* Report header */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 11, color: C.gold, fontWeight: 700, letterSpacing: "0.06em" }}>
                  {report.session_date} · {week}
                </div>
                <div style={{ fontSize: 10, color: C.white, marginTop: 3, maxWidth: 480 }}>{report.headline}</div>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                {report.daily_target_hit && <span style={s.pill(C.tealDim, C.teal, C.tealBorder)}>🎯 TARGET HIT</span>}
                {report.daily_loss_hit && <span style={s.pill(C.redDim, C.red, C.redBorder)}>🛑 LOSS LIMIT</span>}
                {report.duration_timer_exits > 0 && <span style={s.pill(C.amberDim, "#F5C875", C.amber)}>⏱ {report.duration_timer_exits} TIMER EXIT{report.duration_timer_exits > 1 ? "S" : ""}</span>}
                <button style={s.btnGhost} onClick={() => setReport(null)}>← New session</button>
              </div>
            </div>

            {/* Metric grid */}
            <div style={{ display: "flex", gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
              <MetricCard label="NET P&L" value={fmt$(report.net_pnl)} color={pnlColor(report.net_pnl)} />
              <MetricCard label="WIN RATE" value={fmtPct(report.win_rate)} color={report.win_rate >= 60 ? C.teal : report.win_rate >= 45 ? C.gold : C.red} />
              <MetricCard label="TRADES" value={`${report.winners}W / ${report.losers}L`} color={C.silver} />
              <MetricCard label="PROFIT FACTOR" value={report.profit_factor > 0 ? report.profit_factor.toFixed(2) : "—"} color={report.profit_factor >= 1.5 ? C.teal : report.profit_factor >= 1 ? C.gold : C.red} />
              <MetricCard label="AVG WIN" value={report.avg_win > 0 ? fmt$(report.avg_win) : "—"} color={C.teal} />
              <MetricCard label="AVG LOSS" value={report.avg_loss < 0 ? fmt$(report.avg_loss) : "—"} color={C.red} />
              <MetricCard label="AVG MAE" value={report.avg_mae !== 0 ? fmt$(report.avg_mae) : "—"} color={C.silver} />
              <MetricCard label="CONTRACTS" value={report.contracts || "—"} color={C.silver} />
            </div>

            {/* Direction split */}
            <div style={{ display: "flex", gap: 6, marginBottom: 10 }}>
              <div style={{ ...s.metricCard, flex: "none", display: "flex", gap: 14, alignItems: "center" }}>
                <div style={{ ...s.metricLabel }}>DIRECTION SPLIT</div>
                <span style={{ fontSize: 11, color: C.teal, fontFamily: "monospace" }}>↑ {report.directions?.long || 0} L</span>
                <span style={{ fontSize: 11, color: C.red, fontFamily: "monospace" }}>↓ {report.directions?.short || 0} S</span>
              </div>
              {report.max_consec_losses > 0 && (
                <div style={{ ...s.metricCard, flex: "none" }}>
                  <div style={s.metricLabel}>MAX CONSEC. LOSSES</div>
                  <div style={{ ...s.metricVal, fontSize: 16, color: report.max_consec_losses >= 3 ? C.red : C.gold }}>{report.max_consec_losses}</div>
                </div>
              )}
            </div>

            {/* Flags */}
            {report.flags && report.flags.length > 0 && (
              <div style={{ marginBottom: 10 }}>
                {report.flags.map((f, i) => <div key={i} style={s.flag}>⚠ {f}</div>)}
              </div>
            )}

            {/* Performance summary */}
            <SectionBlock dotColor={C.teal} label="PERFORMANCE SUMMARY">
              <p style={s.prose}>{report.performance_summary}</p>
            </SectionBlock>

            {/* Asian level observations */}
            <SectionBlock dotColor={C.cyan} label="ASIAN LEVEL OBSERVATIONS — v1.6.1 KEY METRIC">
              <p style={s.prose}>{report.asian_level_observations}</p>
            </SectionBlock>

            {/* Signal quality */}
            <SectionBlock dotColor={C.gold} label="SIGNAL QUALITY">
              <p style={s.prose}>{report.signal_quality}</p>
            </SectionBlock>

            {/* Open questions */}
            <SectionBlock dotColor={C.amber} label="v1.7 OPEN QUESTIONS UPDATE">
              <div style={{ ...s.prose, whiteSpace: "pre-line" }}>{report.open_questions_update}</div>
            </SectionBlock>

            {/* Anomalies */}
            {report.anomalies && report.anomalies !== "None observed" && (
              <SectionBlock dotColor={C.red} label="ANOMALIES">
                <p style={{ ...s.prose, color: "#F5C875" }}>{report.anomalies}</p>
              </SectionBlock>
            )}

            {/* Tracker update */}
            <SectionBlock dotColor={C.silver} label="DEVELOPMENT TRACKER — COPY TO FORWARD TEST LOG">
              <div style={{ marginBottom: 6, fontSize: 8, color: C.muted }}>Click to copy to clipboard</div>
              <div style={s.trackerBox} onClick={copyTracker}>
                {copied ? "✓ Copied!" : report.tracker_update}
              </div>
            </SectionBlock>
          </>
        )}
      </div>
    </div>
  );
}
