/* Position Statement Builder: interactive demo
 * Three text inputs, live-builds a Position Statement preview.
 * After all three are filled, the user can ask the Companion to refine
 * the draft and then approve, edit, or regenerate.
 */
const { useState, useRef } = React;

function PositionBuilder() {
  const [stance, setStance] = useState('');
  const [matters, setMatters] = useState('');
  const [redline, setRedline] = useState('');
  // refine state: 'idle' | 'thinking' | 'review' | 'approved'
  const [refineState, setRefineState] = useState('idle');
  const [refined, setRefined] = useState({ stance: '', matters: '', redline: '' });
  const [error, setError] = useState('');
  const reqRef = useRef(0);

  const filled = [stance, matters, redline].filter(s => s.trim().length > 4).length;
  const allFilled = filled === 3;
  const project = "portfolio-redesign";
  const today = new Date().toISOString().slice(0, 10);

  // What we render in the preview file: refined draft if approved, else live input.
  const showRefined = refineState === 'review' || refineState === 'approved';
  const display = {
    stance: showRefined ? refined.stance : stance,
    matters: showRefined ? refined.matters : matters,
    redline: showRefined ? refined.redline : redline,
  };

  async function refine() {
    if (!allFilled) return;
    setError('');
    setRefineState('thinking');
    const myReq = ++reqRef.current;

    const prompt = `You are a writing coach helping a designer sharpen a "Position Statement", a short doc they write BEFORE an AI tool touches their project. The goal is to capture their direction in their own voice so AI doesn't drift it.

Their rough answers:
1. Their stance / what they're making: """${stance.trim()}"""
2. What matters most (would be lost if AI rewrote from scratch): """${matters.trim()}"""
3. What they will not compromise on: """${redline.trim()}"""

Refine each answer. Keep their voice; do not make it corporate. Tighten wording, sharpen specifics, fix grammar. Each refined answer should be 1-2 sentences, max ~30 words. Do not invent details they didn't include.

Reply with ONLY a JSON object, no prose, no markdown fences:
{"stance":"...","matters":"...","redline":"..."}`;

    try {
      const text = await window.claude.complete(prompt);
      // Tolerate code fences just in case.
      const cleaned = text.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/i, '').trim();
      const parsed = JSON.parse(cleaned);
      if (myReq !== reqRef.current) return; // stale
      if (!parsed.stance || !parsed.matters || !parsed.redline) {
        throw new Error('missing fields');
      }
      setRefined({
        stance: String(parsed.stance).trim(),
        matters: String(parsed.matters).trim(),
        redline: String(parsed.redline).trim(),
      });
      setRefineState('review');
    } catch (e) {
      if (myReq !== reqRef.current) return;
      setError("Couldn't parse the response. Edit your draft and try again.");
      setRefineState('idle');
    }
  }

  function approve() { setRefineState('approved'); }
  function rejectBack() { setRefineState('idle'); }

  // Step 4 status helpers
  const step4Done = refineState === 'approved';
  const step4Active = allFilled && !step4Done;

  return (
    <div className="demo">
      <div className="demo__bar">
        <div className="demo__title"><span className="mark">P</span>Position Statement Builder</div>
        <span className="pill pill--agent"><span className="dot"/>{step4Done ? 'approved' : `${filled}/3 answered`}</span>
      </div>
      <div className="demo__body">
        <div className="pb-grid">
          <div className="stack">
            <div className="pb-step">
              <div className="pb-step__head"><span className={"num " + (stance.trim().length > 4 ? "num--done" : "")}>{stance.trim().length > 4 ? "✓" : "1"}</span> 01 · Your stance</div>
              <p className="pb-step__q">What are you making? State your direction in your own words.</p>
              <textarea className="pb-input" placeholder="A portfolio site that reflects my design practice, not a template." value={stance} onChange={e => { setStance(e.target.value); if (refineState !== 'idle') setRefineState('idle'); }} />
            </div>
            <div className="pb-step">
              <div className="pb-step__head"><span className={"num " + (matters.trim().length > 4 ? "num--done" : "")}>{matters.trim().length > 4 ? "✓" : "2"}</span> 02 · What matters most</div>
              <p className="pb-step__q">What would be lost if AI rewrote it from scratch?</p>
              <textarea className="pb-input" placeholder="The visual identity has to feel handcrafted. The site should look like me, not like every other AI-generated portfolio." value={matters} onChange={e => { setMatters(e.target.value); if (refineState !== 'idle') setRefineState('idle'); }} />
            </div>
            <div className="pb-step">
              <div className="pb-step__head"><span className={"num " + (redline.trim().length > 4 ? "num--done" : "")}>{redline.trim().length > 4 ? "✓" : "3"}</span> 03 · What you will not compromise</div>
              <p className="pb-step__q">Where do you draw the line on AI input?</p>
              <textarea className="pb-input" placeholder="AI will not choose my typography or color palette. Those are mine." value={redline} onChange={e => { setRedline(e.target.value); if (refineState !== 'idle') setRefineState('idle'); }} />
              <p className="pb-hint">Rough is fine. The point is to write it before AI sees the project.</p>
            </div>

            {/* Step 4: Refine + approve */}
            <div className={"pb-step pb-refine" + (step4Active ? " pb-refine--active" : "") + (step4Done ? " pb-refine--done" : "")}>
              <div className="pb-step__head">
                <span className={"num " + (step4Done ? "num--done" : "")}>{step4Done ? "✓" : "4"}</span>
                04 · Refine with the Companion
              </div>
              {!allFilled && (
                <p className="pb-step__q" style={{color: 'var(--ink-3)'}}>Fill in the three steps above to unlock.</p>
              )}
              {allFilled && refineState === 'idle' && (
                <React.Fragment>
                  <p className="pb-step__q">Companion will tighten your draft, keep your voice, and ask you to approve.</p>
                  <div className="row" style={{gap: 8}}>
                    <button className="btn btn--agent" onClick={refine}>
                      <span className="dot" style={{background: 'white', opacity: 0.9}}/> Refine my draft
                    </button>
                    <span className="muted" style={{fontSize: 12}}>Nothing is committed until you approve.</span>
                  </div>
                  {error && <p className="pb-hint" style={{color: 'var(--danger, #b54)'}}>{error}</p>}
                </React.Fragment>
              )}
              {refineState === 'thinking' && (
                <div className="pb-refine__thinking">
                  <span className="pb-refine__pulse"/>
                  <span>Companion is reading your draft…</span>
                </div>
              )}
              {refineState === 'review' && (
                <React.Fragment>
                  <p className="pb-step__q">Companion suggests this. Approve to commit, or go back to edit.</p>
                  <div className="pb-diff">
                    <PbDiff label="Stance" before={stance} after={refined.stance}/>
                    <PbDiff label="What matters" before={matters} after={refined.matters}/>
                    <PbDiff label="Will not compromise" before={redline} after={refined.redline}/>
                  </div>
                  <div className="row" style={{gap: 8, flexWrap: 'wrap'}}>
                    <button className="btn btn--agent" onClick={approve}>Approve & commit</button>
                    <button className="btn btn--outline" onClick={refine}>Try again</button>
                    <button className="btn btn--ghost" onClick={rejectBack}>Back to my draft</button>
                  </div>
                </React.Fragment>
              )}
              {refineState === 'approved' && (
                <React.Fragment>
                  <p className="pb-step__q" style={{color: 'var(--ink-2)'}}>
                    Approved. Companion wrote <span className="mono">position-statement.md</span> to the gate.
                  </p>
                  <div className="row" style={{gap: 8}}>
                    <button className="btn btn--ghost" onClick={rejectBack}>Edit again</button>
                  </div>
                </React.Fragment>
              )}
            </div>
          </div>
          <div className="pb-result">
            <div className="pb-result__head">
              <div>
                <div className="pb-result__title">position-statement.md</div>
                <div className="muted mono" style={{fontSize: 11, marginTop: 2}}>projects / {project} / position-statements</div>
              </div>
              <span className={"pill " + (step4Done ? "pill--ok" : "pill--agent")}><span className="dot"/>{step4Done ? 'committed' : (refineState === 'review' ? 'awaiting approval' : 'gate set')}</span>
            </div>
            <div className="pb-result__field">
              <span className="pb-result__label">Project</span>
              <span className="pb-result__value mono">{project}</span>
            </div>
            <div className="pb-result__field">
              <span className="pb-result__label">Date</span>
              <span className="pb-result__value mono">{today}</span>
            </div>
            <div className="pb-result__field">
              <span className="pb-result__label">My stance</span>
              <span className={"pb-result__value" + (display.stance ? "" : " pb-result__value--empty")}>
                {display.stance || "Write your direction in step 1."}
              </span>
            </div>
            <div className="pb-result__field">
              <span className="pb-result__label">What matters most</span>
              <span className={"pb-result__value" + (display.matters ? "" : " pb-result__value--empty")}>
                {display.matters || "Write the irreducible core in step 2."}
              </span>
            </div>
            <div className="pb-result__field">
              <span className="pb-result__label">Will not compromise</span>
              <span className={"pb-result__value" + (display.redline ? "" : " pb-result__value--empty")}>
                {display.redline || "Where you draw the line, in step 3."}
              </span>
            </div>
            <div className="row" style={{marginTop: 'auto', paddingTop: 8, borderTop: '1px solid var(--line)'}}>
              <span className="muted" style={{fontSize: 12}}>
                {step4Done
                  ? 'Approved. AI may now read this file as the gate.'
                  : (refineState === 'review' ? 'Preview shows refined draft. Approve to commit.' : 'Until this exists, AI does not see the project.')}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PbDiff({ label, before, after }) {
  const changed = before.trim() !== after.trim();
  return (
    <div className="pb-diff__row">
      <div className="pb-diff__label">{label}</div>
      <div className="pb-diff__before">{before}</div>
      <div className={"pb-diff__after" + (changed ? "" : " pb-diff__after--same")}>
        {after}
        {!changed && <span className="muted" style={{fontSize: 11, marginLeft: 6}}>(unchanged)</span>}
      </div>
    </div>
  );
}

window.PositionBuilder = PositionBuilder;
