/* ============================================
   PROMPT TUNING — System prompt, retrieval params, API config
   ============================================ */
const DEFAULT_PROMPT = `You are the BJP Operation Reference Assistant.
You answer ONLY using the provided manual excerpts. Every factual claim must end with a citation chip in the form [§section].

Rules:
1. If the excerpts do not contain enough information, say so explicitly. Never invent torque specs, part numbers, or procedures.
2. Always surface safety-critical information (LOTO, PPE, lockable energy sources) in a separate "Safety note" callout when relevant.
3. Use the original units from the manual. Do not convert unless asked.
4. When a procedure has numbered steps, preserve the numbering and order from the source.
5. Respond in the user's language (Indonesian or English) matching their question.

Style: concise, technical, no marketing tone.`;

function PromptTuningScreen() {
  const [prompt, setPrompt] = useState(DEFAULT_PROMPT);
  const [topK, setTopK] = useState(8);
  const [threshold, setThreshold] = useState(0.62);
  const [temperature, setTemperature] = useState(0.2);
  const [reranker, setReranker] = useState(true);
  const [hybrid, setHybrid] = useState(true);
  const [chunkOverlap, setChunkOverlap] = useState(64);

  const [showApiKey, setShowApiKey] = useState(false);
  const [dirty, setDirty] = useState(false);

  // Mark dirty on change
  useEffect(() => {setDirty(true);}, [prompt, topK, threshold, temperature, reranker, hybrid, chunkOverlap]);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">System Configuration</h1>
          <p className="page-subtitle">Retrieval, generation, and infrastructure configuration · changes apply to all sessions on save</p>
        </div>
        <div className="row">
          {dirty && <Badge kind="orange">Unsaved changes</Badge>}
          <button className="btn btn--secondary" onClick={() => {setPrompt(DEFAULT_PROMPT);setTopK(8);setThreshold(0.62);setTemperature(0.2);setDirty(false);}}>Reset to defaults</button>
          <button className="btn btn--primary" onClick={() => setDirty(false)}><Icons.Check size={14} /> Save Configuration</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
        {/* ===== LEFT COLUMN ===== */}
        <div className="col gap-16">
          {/* System Prompt */}
          <Card
            title="System Prompt"
            subtitle="Defines the assistant's behavior and citation requirements"
            right={
            <div className="row">
                <Badge kind="neutral">v23 · saved 2 d ago</Badge>
                <button className="btn btn--ghost btn--sm"><Icons.History /> History</button>
              </div>
            }>
            
            <textarea
              className="textarea"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              style={{ minHeight: 280 }} />
            
            <div className="row" style={{ marginTop: 8 }}>
              <span className="text-xs muted mono">{prompt.length} chars · ~{Math.round(prompt.length / 3.5)} tokens</span>
              <span className="spacer" />
              <button className="btn btn--ghost btn--sm">Insert variable</button>
              <button className="btn btn--ghost btn--sm">Test prompt</button>
            </div>
          </Card>

          {/* API Configuration */}
          <Card title="API Configuration" subtitle="External endpoints, model selection, and credentials">
            <div className="form-group">
              <label className="label">Inference Endpoint <span className="label-hint">Generation model API</span></label>
              <input className="input mono" defaultValue="https://api.anthropic.com/v1/messages" />
            </div>

            <div className="grid-2">
              <div className="form-group">
                <label className="label">Generation Model</label>
                <select className="select">
                  <option>claude-haiku-4.5</option>
                  <option>claude-sonnet-4.5</option>
                  <option>claude-opus-4</option>
                </select>
              </div>
              <div className="form-group">
                <label className="label">Embedding Model</label>
                <select className="select">
                  <option>emb-3-lg · 1536-dim</option>
                  <option>emb-3-sm · 768-dim</option>
                  <option>multilingual-emb-2</option>
                </select>
              </div>
            </div>

            <div className="form-group">
              <label className="label">API Key <span className="label-hint">Rotated 14 days ago · expires in 76 days</span></label>
              <div style={{ position: "relative" }}>
                <input
                  className="input mono"
                  type={showApiKey ? "text" : "password"}
                  defaultValue="sk-bjp-prod-1f87a2c3e9d04b6a8f0c12d3e4f56789"
                  style={{ paddingRight: 110 }} />
                
                <div style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)", display: "flex", gap: 4 }}>
                  <button className="btn btn--ghost btn--sm" onClick={() => setShowApiKey(!showApiKey)}>{showApiKey ? "Hide" : "Reveal"}</button>
                  <button className="btn btn--ghost btn--sm"><Icons.Refresh size={11} /></button>
                </div>
              </div>
            </div>

            <div className="form-group">
              <label className="label">Qdrant Vector Store</label>
              <div className="grid-2">
                <input className="input mono" defaultValue="https://qdrant.bjp.local:6333" />
                <input className="input mono" defaultValue="ors_manuals_v3" />
              </div>
              <div className="text-xs muted" style={{ marginTop: 6 }}>Collection: 1,536-dim · cosine similarity · 13,324 vectors · 4 shards</div>
            </div>
          </Card>
        </div>

        {/* ===== RIGHT COLUMN ===== */}
        <div className="col gap-16">
          {/* Retrieval params */}
          <Card title="Retrieval Parameters" subtitle="Vector search, scoring, and reranking">
            <div className="form-group">
              <label className="label">
                Qdrant Top-K
                <span className="label-hint">Number of chunks to retrieve per query</span>
              </label>
              <div className="row">
                <input
                  className="input mono"
                  type="number"
                  min="1"
                  max="32"
                  value={topK}
                  onChange={(e) => setTopK(parseInt(e.target.value) || 1)}
                  style={{ width: 90, textAlign: "center" }} />
                
                <input
                  type="range"
                  min="1"
                  max="32"
                  value={topK}
                  onChange={(e) => setTopK(parseInt(e.target.value))}
                  style={{ flex: 1, accentColor: "var(--orange-500)" }} />
                
                <span className="muted text-xs mono" style={{ width: 50, textAlign: "right" }}>max 32</span>
              </div>
            </div>

            <SliderRow
              label="Score Threshold"
              hint="Cosine similarity floor — chunks below this are dropped"
              value={threshold}
              onChange={setThreshold}
              min={0}
              max={1}
              step={0.01}
              format={(v) => v.toFixed(2)} />
            

            <SliderRow
              label="Generation Temperature"
              hint="0 = deterministic, 1 = creative. Keep low for factual tasks."
              value={temperature}
              onChange={setTemperature}
              min={0}
              max={1}
              step={0.05}
              format={(v) => v.toFixed(2)} />
            

            <SliderRow
              label="Chunk Overlap (tokens)"
              hint="Token overlap between adjacent chunks at index time"
              value={chunkOverlap}
              onChange={setChunkOverlap}
              min={0}
              max={256}
              step={8}
              format={(v) => v.toString()} />
            

            <div style={{ borderTop: "1px solid var(--ink-200)", margin: "16px -18px 14px" }} />

            <div className="row" style={{ marginBottom: 12 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Hybrid search</div>
                <div className="text-xs muted">Combine vector + BM25 keyword scores</div>
              </div>
              <Toggle on={hybrid} onChange={setHybrid} />
            </div>

            <div className="row">
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Cross-encoder reranker</div>
                <div className="text-xs muted">Adds ~120ms latency, +6.4% citation accuracy</div>
              </div>
              <Toggle on={reranker} onChange={setReranker} />
            </div>
          </Card>

          {/* Quick preview */}
          <Card title="Current Configuration" subtitle="Live preview of effective settings" right={<Badge kind="complete">Validated</Badge>}>
            <div style={{ background: "var(--ink-50)", border: "1px solid var(--ink-200)", borderRadius: 6, padding: 14, fontFamily: "var(--font-mono)", fontSize: 11.5, lineHeight: 1.85 }}>
              <ConfLine k="retrieval.top_k" v={topK} />
              <ConfLine k="retrieval.score_threshold" v={threshold.toFixed(2)} />
              <ConfLine k="retrieval.chunk_overlap" v={chunkOverlap} />
              <ConfLine k="retrieval.hybrid_search" v={hybrid ? "true" : "false"} />
              <ConfLine k="retrieval.reranker" v={reranker ? "enabled" : "disabled"} />
              <ConfLine k="generation.temperature" v={temperature.toFixed(2)} />
              <ConfLine k="generation.model" v={`"haiku-4.5"`} />
              <ConfLine k="generation.max_tokens" v={1024} />
            </div>

            <div style={{ marginTop: 12, padding: 12, background: "var(--orange-50)", border: "1px solid var(--orange-100)", borderRadius: 6 }}>
              <div className="row gap-6">
                <Icons.AlertCircle size={14} />
                <span className="text-xs fw-600" style={{ color: "var(--orange-700)" }}>Save will roll out to 184 active sessions</span>
              </div>
              <div className="text-xs" style={{ color: "var(--ink-700)", marginTop: 4, paddingLeft: 22 }}>
                Active queries will complete with current config. New queries start with the new config.
              </div>
            </div>
          </Card>

        </div>
      </div>
    </>);

}

function SliderRow({ label, hint, value, onChange, min, max, step, format }) {
  return (
    <div className="form-group">
      <label className="label">{label} <span className="label-hint">{hint}</span></label>
      <div className="row gap-12">
        <input
          type="range"
          min={min} max={max} step={step}
          value={value}
          onChange={(e) => onChange(parseFloat(e.target.value))}
          style={{ flex: 1, accentColor: "var(--orange-500)" }} />
        
        <div className="mono" style={{
          width: 72, textAlign: "center",
          background: "var(--ink-50)", border: "1px solid var(--ink-200)",
          padding: "5px 8px", borderRadius: 5, fontWeight: 600, color: "var(--orange-700)"
        }}>{format(value)}</div>
      </div>
      <div className="row" style={{ marginTop: 4 }}>
        <span className="text-xs muted mono">{format(min)}</span>
        <span className="spacer" />
        <span className="text-xs muted mono">{format(max)}</span>
      </div>
    </div>);

}

function ConfLine({ k, v }) {
  return (
    <div>
      <span style={{ color: "var(--navy-700)" }}>{k}</span>
      <span style={{ color: "var(--ink-400)" }}> = </span>
      <span style={{ color: "var(--orange-700)", fontWeight: 600 }}>{v}</span>
    </div>);

}

window.PromptTuningScreen = PromptTuningScreen;