// Sandbox: offerte-agent processing an offerte-aanvraag
// Two modes:
//  - Preset mode: canned fast reliable result
//  - Custom mode: user edited text -> calls window.claude.complete for a live concept offer

const SAMPLE_REQUESTS = {
  bouw: `Beste Demo BV,

We hebben voor een nieuwbouwproject in Tilburg het volgende nodig, graag een offerte:

- 40 stuks HEB 200 balken, lengte 6 meter
- 25 stuks IPE 180, lengte 8 meter
- 200m² staalplaat 8mm, rechthoekig 2x3m
- Levering bij voorkeur week 47

Klantnr: 2041 (Repetive Bouw)
Met vriendelijke groet,
Sam (Repetive Bouw)`,

  machine: `Hoi,

Voor een nieuwe productielijn hebben we nodig:
- 12x ronde buis DN80 dikwandig, 3m
- 8x UNP 160, 4m lang
- 60kg lasstaven gewoon staal

Graag z.s.m. offerte. We zijn vaste klant (Klantnr 1518 - Repetive Machinebouw).

Groet, Robin`,

  kleine: `Goedemiddag,

Kunnen jullie een prijs afgeven op:
- 2 stuks HEA 140, 3 meter

Eenmalige aanvraag. Firma Repetive.
Alvast bedankt!`
};

const SAMPLE_RESULTS = {
  bouw: {
    klant: 'Repetive Bouw · Klantnr 2041',
    korting: '7% (staffel A, >€10k)',
    regels: [
      { code: 'HEB200-6', omschr: 'HEB 200 balken, 6 m', aantal: 40, prijs: 168.50, totaal: 6740.00 },
      { code: 'IPE180-8', omschr: 'IPE 180 balken, 8 m', aantal: 25, prijs: 142.00, totaal: 3550.00 },
      { code: 'PLT-8-2X3', omschr: 'Staalplaat 8mm · 2×3m', aantal: 33, prijs: 189.00, totaal: 6237.00 }
    ],
    subtotaal: 16527.00,
    korting_bedrag: -1156.89,
    totaal: 15370.11,
    levering: 'Week 47 ✓ op voorraad'
  },
  machine: {
    klant: 'Repetive Machinebouw · Klantnr 1518',
    korting: '5% (vaste klant)',
    regels: [
      { code: 'RND-DN80-DW', omschr: 'Ronde buis DN80 dikwandig, 3m', aantal: 12, prijs: 86.00, totaal: 1032.00 },
      { code: 'UNP160-4', omschr: 'UNP 160, 4m', aantal: 8, prijs: 94.50, totaal: 756.00 },
      { code: 'LAS-STD', omschr: 'Lasstaven gewoon staal', aantal: 60, prijs: 4.20, totaal: 252.00 }
    ],
    subtotaal: 2040.00,
    korting_bedrag: -102.00,
    totaal: 1938.00,
    levering: 'Leverbaar deze week'
  },
  kleine: {
    klant: 'Firma Repetive · nieuwe klant',
    korting: 'Geen (eenmalige aanvraag)',
    regels: [
      { code: 'HEA140-3', omschr: 'HEA 140, 3m', aantal: 2, prijs: 67.00, totaal: 134.00 }
    ],
    subtotaal: 134.00,
    korting_bedrag: 0,
    totaal: 134.00,
    levering: 'Op voorraad'
  }
};

const STEPS = [
  { t: 'Aanvraag gelezen', d: 'Klant, producten, en voorkeuren geëxtraheerd' },
  { t: 'Klant opgezocht in Exact', d: 'Klantnr gematcht, historie gecheckt' },
  { t: 'Producten gematcht in catalogus', d: 'Semantische match op omschrijving' },
  { t: 'Pricing opgehaald', d: 'Actuele prijslijst per product' },
  { t: 'Kortingsregels toegepast', d: 'Staffel + klant-specifieke korting' },
  { t: 'Voorraad & levertijd gecheckt', d: 'Exact voorraadstand geraadpleegd' },
  { t: 'Concept-offerte klaargezet', d: 'In Exact, met review-taak voor sales' }
];

// Detect which preset the text currently matches (if any)
const detectPreset = (text) => {
  for (const k of Object.keys(SAMPLE_REQUESTS)) {
    if (SAMPLE_REQUESTS[k] === text) return k;
  }
  return null;
};

const Sandbox = () => {
  const [text, setText] = React.useState(SAMPLE_REQUESTS.bouw);
  const [running, setRunning] = React.useState(false);
  const [activeStep, setActiveStep] = React.useState(-1);
  const [showResult, setShowResult] = React.useState(false);
  const [liveResult, setLiveResult] = React.useState(null); // result for custom input
  const [error, setError] = React.useState(null);

  const activePreset = detectPreset(text);
  const isCustom = !activePreset;

  const runPreset = (preset) => {
    setRunning(true);
    setShowResult(false);
    setActiveStep(-1);
    setError(null);
    setLiveResult(null);
    STEPS.forEach((_, i) => {
      setTimeout(() => setActiveStep(i), 400 + i * 380);
    });
    setTimeout(() => {
      setRunning(false);
      setShowResult(true);
    }, 400 + STEPS.length * 380 + 200);
  };

  const runCustom = async () => {
    setRunning(true);
    setShowResult(false);
    setActiveStep(-1);
    setError(null);
    setLiveResult(null);

    // Animate steps 0..4 while we wait for the LLM
    STEPS.slice(0, 5).forEach((_, i) => {
      setTimeout(() => setActiveStep(i), 400 + i * 380);
    });

    try {
      const prompt = `Je bent een offerte-agent voor Demo BV (staalgroothandel). De klant stuurt een offerte-aanvraag. Jij moet een concept-offerte genereren.

Regels:
- Bedenk plausibele artikelcodes en prijzen (staal in NL, bereik €40-€300 per stuk). Als de klant iets noemt dat je niet kent, maak een redelijke inschatting.
- Als klantnaam/nummer genoemd: gebruik die. Anders: "Onbekende klant · nieuwe relatie"
- Kortingslogica: >€10k → 7%, >€5k → 5%, vaste klant → 5%, anders: geen
- Levering: meestal "Op voorraad" of "Week X". Verzin iets redelijks.

Geef je antwoord ALLEEN als geldige JSON in dit exacte schema (geen markdown, geen uitleg eromheen):
{
  "klant": "Naam · Klantnr 1234 (of 'nieuwe relatie')",
  "korting": "beschrijving kortingsregel",
  "regels": [{"code":"AAA-B-C","omschr":"omschrijving","aantal":1,"prijs":0.00,"totaal":0.00}],
  "subtotaal": 0.00,
  "korting_bedrag": 0.00,
  "totaal": 0.00,
  "levering": "beschrijving levertijd"
}

Aanvraag:
${text}`;

      const response = await window.claude.complete(prompt);
      // Parse JSON out
      let parsed;
      try {
        const jsonMatch = response.match(/\{[\s\S]*\}/);
        parsed = JSON.parse(jsonMatch ? jsonMatch[0] : response);
      } catch(e) {
        throw new Error('Kon antwoord niet parsen');
      }
      setLiveResult(parsed);
      // Finish the step animation
      setActiveStep(4);
      setTimeout(() => setActiveStep(5), 300);
      setTimeout(() => setActiveStep(6), 600);
      setTimeout(() => {
        setRunning(false);
        setShowResult(true);
      }, 900);
    } catch (e) {
      console.error(e);
      setError(e.message || 'Er ging iets mis');
      setRunning(false);
    }
  };

  const run = () => {
    if (running) return;
    if (isCustom) runCustom();
    else runPreset(activePreset);
  };

  const setPreset = (k) => {
    setText(SAMPLE_REQUESTS[k]);
    setShowResult(false);
    setActiveStep(-1);
    setLiveResult(null);
    setError(null);
  };

  const result = showResult ? (liveResult || SAMPLE_RESULTS[activePreset]) : null;
  const fmt = (n) => Number(n || 0).toLocaleString('nl-NL', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <section className="sandbox" id="sandbox">
      <div className="sandbox-wrap">
        <div className="sandbox-head">
          <div>
            <div className="eyebrow-big"><span className="bar"></span> Live proberen</div>
            <h2 className="section-h">Stuur de offerte-agent een offerte-aanvraag.</h2>
          </div>
        </div>

        <div className="sandbox-frame">
          <div className="sb-input">
            <div className="sb-input-head">
              <span>Inkomende aanvraag</span>
              <span className={'demo-badge ' + (isCustom ? 'custom' : '')}>{isCustom ? '● Eigen input · live' : '○ Voorbeeld-aanvraag'}</span>
            </div>
            <div className="from">Van: klant@voorbeeld.nl → verkoop@demo.nl</div>
            <textarea
              value={text}
              onChange={e => { setText(e.target.value); setShowResult(false); setLiveResult(null); setError(null); }}
              disabled={running}
              readOnly
            />
            <div className="presets">
              {[['bouw', 'Bouw-aanvraag'], ['machine', 'Machinebouw'], ['kleine', 'Kleine order']].map(([k, l]) => (
                <button key={k} className="preset" onClick={() => setPreset(k)} disabled={running} style={activePreset === k ? {borderColor: 'var(--brand-purple)', color: 'var(--brand-purple)', background: 'var(--surface-tint-purple)'} : {}}>{l}</button>
              ))}
            </div>
            <button className="run" onClick={run} disabled={running || !text.trim()}>
              {running ? 'Agent werkt…' : isCustom ? '→ Stuur naar offerte-agent (live)' : '→ Stuur naar offerte-agent'}
            </button>
          </div>

          <div className="sb-output">
            <div className="sb-output-head">
              <div className="max-badge">
                <div className="max-avatar">O</div>
                <span>Offerte-agent</span>
              </div>
              <span>{running ? 'verwerken' : showResult ? 'klaar voor review' : 'standby'}</span>
            </div>

            {!running && !showResult && !error && (
              <div className="sb-empty">
                <div className="big">De offerte-agent staat stand-by.</div>
                <div>Druk op "Stuur naar offerte-agent" om een voorbeeld te zien draaien.</div>
              </div>
            )}

            {error && (
              <div className="sb-empty">
                <div className="big" style={{color: 'var(--tint-pink-deep)'}}>Oeps.</div>
                <div>{error}</div>
                <button className="run" style={{marginTop: 16, display: 'inline-block', width: 'auto', padding: '8px 18px'}} onClick={run}>Opnieuw proberen</button>
              </div>
            )}

            {(running || showResult) && !error && (
              <>
                {STEPS.map((s, i) => (
                  <div key={i} className={'sb-step' + (i <= activeStep ? ' done' : '') + (i === activeStep + 1 && running ? ' active' : '')} style={{ animationDelay: `${i * 60}ms` }}>
                    <div className="dot">{i <= activeStep ? '✓' : ''}</div>
                    <div className="body">
                      <div className="t">{s.t}</div>
                      <div className="d">{s.d}</div>
                    </div>
                    <div className="timing">{i <= activeStep ? `${(0.3 + Math.random() * 0.7).toFixed(1)}s` : '·'}</div>
                  </div>
                ))}

                {showResult && result && (
                  <div className="sb-result">
                    <h5>
                      Concept-offerte {(result.klant || '').split('·')[0].trim()}
                      <span className="badge">✓ KLAAR VOOR REVIEW</span>
                    </h5>
                    <div style={{fontSize: '12px', color: 'var(--ink-4)', marginBottom: '12px'}}>
                      Klant: <strong style={{color: 'var(--ink-2)'}}>{result.klant}</strong> · Korting-regel: {result.korting}
                    </div>
                    <table>
                      <thead>
                        <tr>
                          <th>Artikel</th>
                          <th style={{textAlign: 'right'}}>Aantal</th>
                          <th style={{textAlign: 'right'}}>Prijs</th>
                          <th style={{textAlign: 'right'}}>Totaal</th>
                        </tr>
                      </thead>
                      <tbody>
                        {(result.regels || []).map((r, i) => (
                          <tr key={i}>
                            <td><div>{r.omschr}</div><div style={{fontSize: '10px', color: 'var(--ink-4)', marginTop: '2px'}}>{r.code}</div></td>
                            <td className="num">{r.aantal}</td>
                            <td className="num">€ {fmt(r.prijs)}</td>
                            <td className="num">€ {fmt(r.totaal)}</td>
                          </tr>
                        ))}
                        <tr>
                          <td colSpan="3" style={{fontSize: '12px', color: 'var(--ink-4)'}}>Subtotaal</td>
                          <td className="num">€ {fmt(result.subtotaal)}</td>
                        </tr>
                        {Number(result.korting_bedrag) !== 0 && (
                          <tr>
                            <td colSpan="3" style={{fontSize: '12px', color: 'var(--ink-4)'}}>Korting ({result.korting})</td>
                            <td className="num" style={{color: 'var(--tint-pink-deep)'}}>€ {fmt(result.korting_bedrag)}</td>
                          </tr>
                        )}
                        <tr className="total">
                          <td colSpan="3">Totaal</td>
                          <td className="num">€ {fmt(result.totaal)}</td>
                        </tr>
                      </tbody>
                    </table>
                    <div className="footer">
                      <span>Levering: {result.levering}</span>
                      <button className="review-btn">Review & verstuur →</button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

window.Sandbox = Sandbox;
