// Screen 2 — Crea con AI: descrizione → POST /assistants/build → bozza nell'editor.
// Il dominio NON si sceglie qui: è ereditato dal contesto attivo (dominio
// selezionato nella sidebar/console) e arriva come prop `domain`, mostrato
// in sola lettura. Nessuna lista domini locale.
const { Card, CardBody, TextField, Button, Banner, Icon, Badge } = window.AriaDesignSystem_af77ab;

function CreateWithAI({ domain, onGenerated, onCancel }) {
  const [description, setDescription] = React.useState("");
  const [phase, setPhase] = React.useState("input"); // input | building
  const [attempt, setAttempt] = React.useState(0);
  const [error, setError] = React.useState(null);     // errore inatteso (rete/5xx)
  const [problems, setProblems] = React.useState(null); // 422: l'AI non ha prodotto una config valida

  const examples = [
    "Assistente per prenotare appuntamenti in officina: chiede targa, servizio e data preferita.",
    "Assistente che risponde a domande sui resi e apre una pratica se l'ordine è idoneo.",
  ];

  async function build() {
    setPhase("building");
    setAttempt(1);
    setError(null);
    setProblems(null);
    try {
      // POST /assistants/build { description, domain } → 200 {config, attempts, pending} | 422 {problems, attempts}
      const res = await window.AriaData.buildAssistant({ description, domain });
      if (res.ok) {
        setAttempt(res.attempts || 1);
        onGenerated({ config: res.config, attempts: res.attempts, pending: res.pending, fromAI: true });
        return;
      }
      // 422: la generazione non ha prodotto una config valida → mostra i problemi, torna all'input.
      setProblems(res.problems || []);
      setAttempt(res.attempts || 0);
      setPhase("input");
    } catch (err) {
      setError(err);
      setPhase("input");
    }
  }

  return (
    <div style={{ padding: 28, maxWidth: 720, width: "100%", margin: "0 auto" }}>
      <Card>
        <CardBody>
          {phase === "input" ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Banner tone="info" title="Genera una bozza">
                Descrivi l'assistente in linguaggio naturale. Aria genera una configurazione conforme;
                i valori che non può inventare (id, nome, URL e token) restano <b>da completare</b>.
              </Banner>

              {error && (
                <Banner tone="danger" title="Generazione non riuscita" icon="alert-circle">
                  {error.message || "Errore inatteso. Riprova."}
                </Banner>
              )}
              {problems && (
                <Banner tone="warning" title={`Aria non ha prodotto una configurazione valida${attempt ? ` (${attempt} tentativi)` : ""}`} icon="alert-triangle">
                  <span>Prova a riformulare la descrizione con più dettagli.</span>
                  {problems.length > 0 && (
                    <ul style={{ margin: "8px 0 0", paddingLeft: 18, fontSize: 13 }}>
                      {problems.map((p, i) => (
                        <li key={i}><b>{p.path || "config"}</b>{p.message ? ` — ${p.message}` : ""}</li>
                      ))}
                    </ul>
                  )}
                </Banner>
              )}

              {/* Dominio: contesto in sola lettura, ereditato dal dominio attivo (sidebar). */}
              <div style={{
                display: "flex", alignItems: "center", gap: 8, alignSelf: "flex-start",
                padding: "6px 12px", borderRadius: "var(--radius-pill)",
                background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)",
              }}>
                <Icon name="globe" size={15} color="var(--text-subtle)" />
                <span style={{ font: "var(--text-label)", color: "var(--text-subtle)" }}>Dominio</span>
                <span style={{ font: "var(--fw-medium) var(--fs-body)/1 var(--font-sans)", color: "var(--text-strong)" }}>«{domain}»</span>
              </div>
              <TextField
                label="Descrizione" required multiline rows={5}
                placeholder="Es. Assistente di supporto che controlla lo stato degli ordini e avvia i resi…"
                value={description} onChange={(e) => setDescription(e.target.value)}
              />
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {examples.map((ex, i) => (
                  <button key={i} onClick={() => setDescription(ex)} style={{
                    border: "1px solid var(--border-subtle)", background: "var(--surface-sunken)",
                    color: "var(--text-muted)", borderRadius: "var(--radius-pill)", padding: "5px 12px",
                    fontSize: 12, cursor: "pointer", textAlign: "left", maxWidth: "100%",
                  }}>{ex}</button>
                ))}
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 4 }}>
                <Button variant="secondary" onClick={onCancel}>Annulla</Button>
                <Button iconLeft={<Icon name="sparkles" />} disabled={!description.trim()} onClick={build}>Genera bozza</Button>
              </div>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, padding: "32px 0" }}>
              <span style={{
                width: 48, height: 48, borderRadius: 14, background: "var(--sage-100)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                animation: "aria-pulse 1.4s var(--ease-standard) infinite",
              }}>
                <Icon name="sparkles" size={24} color="var(--primary-text)" />
              </span>
              <div style={{ font: "var(--text-h3)", color: "var(--text-strong)" }}>Generazione in corso…</div>
              <Badge tone="neutral">Tentativo {attempt}</Badge>
              <div style={{ fontSize: 13, color: "var(--text-muted)", maxWidth: 380, textAlign: "center" }}>
                Aria sta proponendo skill, attributi e azioni a partire dalla descrizione.
              </div>
            </div>
          )}
        </CardBody>
      </Card>
      <style>{`@keyframes aria-pulse { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.08); opacity: 0.7; } }
        @media (prefers-reduced-motion: reduce) { [style*="aria-pulse"] { animation: none !important; } }`}</style>
    </div>
  );
}

Object.assign(window, { CreateWithAI });
