// UC-A3 Pubblica Richiesta — Single-page form
// Sections: Tipo di servizio, Brief (con AI assist), Allegati, Budget, Deadline, Visibilità

const PR_Icons = window.SonaraIcons;
const { useState: useStatePR, useRef: useRefPR } = React;

const SERVICE_TYPES = [
  { id: "beat",    label: "Beat",          sub: "Strumentale pronta o custom",   icon: <PR_Icons.music size={26}/>,     popular: true },
  { id: "mix",     label: "Mix",           sub: "Bilancia, EQ, dinamica",        icon: <PR_Icons.mixer size={26}/>,     popular: true },
  { id: "master",  label: "Master",        sub: "Loudness e finitura per release", icon: <PR_Icons.equalizer size={26}/> },
  { id: "vocal",   label: "Vocal prod",    sub: "Tuning, doubles, comping",      icon: <PR_Icons.mic size={26}/> },
  { id: "ep",      label: "Producer per EP", sub: "Direzione artistica completa", icon: <PR_Icons.collaboration size={26}/> },
  { id: "manager", label: "Manager",       sub: "Rappresentanza e A&R",          icon: <PR_Icons.user size={26}/> },
  { id: "other",   label: "Altro",         sub: "Specifica nel brief",           icon: <PR_Icons.more size={26}/> },
];

const BRIEF_TEMPLATES = {
  beat:    "Sto cercando una base trap dark, 140 BPM circa, 808 sporche e atmosfera notturna. Riferimenti: Travis Scott, Sfera Ebbasta — Tran Tran. Mi serve per un singolo da pubblicare a marzo. Voce maschile baritonale.",
  mix:     "Ho 12 stems di un brano indie-pop, voce + chitarra acustica + basso + batteria + synth. Cerco un mix caldo, vintage, con la voce davanti. Riferimenti: Phoebe Bridgers, Iosonouncane.",
  master:  "Ho il mix finale di un singolo elettronico, lunghezza 3:42. Vorrei un master loud ma non spinto, con dinamica preservata. Target: streaming Spotify e vinile. Riferimenti: Bicep, Floating Points.",
  vocal:   "Cerco vocal producer per un brano pop in italiano. Ho la voce lead già registrata, mi servono cori, doubles, ad-libs e tuning naturale. Stile riferimento: Sangiovanni, Rkomi.",
  ep:      "Sto preparando un EP di 5 brani indie-elettronico. Cerco un producer che mi accompagni dall'arrangiamento al master. Ho già le demo in voce-piano. Tempi: 3 mesi. Budget complessivo da definire.",
  manager: "Sono un'artista emergente con 80k stream mensili e una release ogni 2 mesi. Cerco un manager che mi supporti su strategia release, booking live e contatti label. Vivo a Milano.",
  other:   "",
};

const BUDGET_PRESETS = [
  { id: "p1", label: "€50–150",  min: 50,  max: 150 },
  { id: "p2", label: "€150–400", min: 150, max: 400 },
  { id: "p3", label: "€400–800", min: 400, max: 800 },
  { id: "p4", label: "€800+",    min: 800, max: 2000 },
  { id: "open", label: "Decideremo insieme", min: null, max: null },
];

const DEADLINE_PRESETS = [
  { id: "d1", label: "Entro 1 settimana", days: 7 },
  { id: "d2", label: "Entro 2 settimane", days: 14 },
  { id: "d3", label: "Entro 1 mese",      days: 30 },
  { id: "flex", label: "Flessibile",      days: null },
];

function PubblicaRichiestaPage() {
  const [serviceType, setServiceType] = useStatePR(null);
  const [brief, setBrief] = useStatePR("");
  const [aiOpen, setAiOpen] = useStatePR(false);
  const [aiLoading, setAiLoading] = useStatePR(false);
  const [aiError, setAiError] = useStatePR(null);
  const [aiSuggestion, setAiSuggestion] = useStatePR(null);
  const [files, setFiles] = useStatePR([]);
  const [budget, setBudget] = useStatePR("p2");
  const [budgetMin, setBudgetMin] = useStatePR(150);
  const [budgetMax, setBudgetMax] = useStatePR(400);
  const [deadline, setDeadline] = useStatePR("d2");
  const [deadlineDate, setDeadlineDate] = useStatePR("");
  const [visibility, setVisibility] = useStatePR("public");
  const [submitted, setSubmitted] = useStatePR(false);

  const fileRef = useRefPR(null);

  // Validation
  const briefMin = 40;
  const briefValid = brief.trim().length >= briefMin;
  const canSubmit = serviceType && briefValid;
  const briefPct = Math.min(100, Math.round((brief.length / 400) * 100));
  const tooShort = brief.length > 0 && brief.length < briefMin;

  // Handlers
  const onFiles = (filelist) => {
    const arr = Array.from(filelist || []).map(f => ({
      id: Math.random().toString(36).slice(2),
      name: f.name,
      size: f.size,
      type: guessType(f),
    }));
    setFiles(prev => [...prev, ...arr].slice(0, 5));
  };

  const askAI = async () => {
    if (!serviceType) return;
    setAiOpen(true);
    setAiLoading(true);
    setAiError(null);
    setAiSuggestion(null);
    const promptCtx = SERVICE_TYPES.find(s => s.id === serviceType);
    const userBrief = brief.trim();
    try {
      const prompt = `Sei un assistente che aiuta artisti italiani a scrivere un brief chiaro per pubblicare una richiesta su SONARA, una piattaforma per producer musicali.

L'artista cerca: ${promptCtx.label} (${promptCtx.sub}).

${userBrief ? `Bozza dell'artista:\n"${userBrief}"\n\nRiscrivi e completa questo brief` : "L'artista non ha ancora scritto nulla. Scrivi un esempio di brief"}, in italiano, max 500 caratteri, includendo: cosa cerca esattamente, riferimenti artistici (1-2), mood/atmosfera, eventuale BPM o tonalità, contesto d'uso (singolo, EP, demo).

Tono: diretto, da musicista a musicista. Niente formattazione markdown, niente intestazioni. Solo testo continuo. Inizia direttamente col contenuto.`;
      const text = await window.claude.complete(prompt);
      setAiSuggestion(text.trim());
    } catch (e) {
      setAiError("Impossibile generare un suggerimento ora. Riprova tra poco.");
    } finally {
      setAiLoading(false);
    }
  };

  const acceptAI = () => {
    if (aiSuggestion) setBrief(aiSuggestion);
    setAiOpen(false);
    setAiSuggestion(null);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setSubmitted(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (submitted) {
    return <PRSuccess
      onNew={() => { setSubmitted(false); setServiceType(null); setBrief(""); setFiles([]); setBudget("p2"); setDeadline("d2"); }}
      type={SERVICE_TYPES.find(s => s.id === serviceType)?.label}
    />;
  }

  const selSvc  = SERVICE_TYPES.find(s => s.id === serviceType);
  const selBudg = BUDGET_PRESETS.find(b => b.id === budget);
  const selDdln = DEADLINE_PRESETS.find(d => d.id === deadline);

  return (
    <div className="page pr-page" data-screen-label="Pubblica Richiesta">
      <header className="pr-head">
        <div className="pr-head-l">
          <a href="Dashboard.html" className="pr-back">
            <PR_Icons.arrowLeft size={14} className="pr-back-ic"/> Dashboard
          </a>
          <h1 className="pr-title">Pubblica una richiesta</h1>
          <p className="pr-sub">
            Descrivi cosa cerchi — i producer in linea col tuo profilo ti faranno un'offerta.
            Hai <strong>2 richieste su 3</strong> attive. <a href="#" className="pr-link" onClick={(e) => e.preventDefault()}>Come funziona →</a>
          </p>
        </div>
        <div className="pr-head-r">
          <span className="pr-quota-pill">
            <PR_Icons.target size={13}/> 2 / 3 attive
          </span>
        </div>
      </header>

      <div className="pr-layout">
        <form className="pr-form" onSubmit={onSubmit}>
          {/* ============== Tipo di servizio ============== */}
          <PRSection num={1} title="Cosa cerchi?" required>
            <div className="pr-svc-grid">
              {SERVICE_TYPES.map(s => (
                <button
                  type="button"
                  key={s.id}
                  className={`pr-svc-card ${serviceType === s.id ? "active" : ""}`}
                  onClick={() => setServiceType(s.id)}
                  aria-pressed={serviceType === s.id}
                >
                  {s.popular && <span className="pr-svc-pop">Più richiesto</span>}
                  <span className="pr-svc-ic">{s.icon}</span>
                  <span className="pr-svc-label">{s.label}</span>
                  <span className="pr-svc-sub">{s.sub}</span>
                  {serviceType === s.id && (
                    <span className="pr-svc-tick" aria-hidden>
                      <PR_Icons.check size={12}/>
                    </span>
                  )}
                </button>
              ))}
            </div>
          </PRSection>

          {/* ============== Brief ============== */}
          <PRSection num={2} title="Brief" required hint="Più sei specifico, migliori saranno le offerte">
            <div className="pr-brief-wrap">
              <textarea
                className={`pr-textarea ${tooShort ? "warn" : ""}`}
                value={brief}
                onChange={(e) => setBrief(e.target.value)}
                placeholder={
                  serviceType
                    ? `Esempio: ${BRIEF_TEMPLATES[serviceType].slice(0, 80)}…`
                    : "Cosa stai cercando? Riferimenti artistici, mood, BPM, contesto d'uso…"
                }
                maxLength={2000}
                rows={6}
              />
              <div className="pr-brief-foot">
                <div className="pr-brief-l">
                  <button
                    type="button"
                    className="pr-ai-btn"
                    onClick={askAI}
                    disabled={!serviceType || aiLoading}
                    title={!serviceType ? "Scegli prima cosa cerchi" : "Aiutami a scrivere"}
                  >
                    <PR_Icons.zap size={13}/>
                    {aiLoading ? "Genero…" : (brief.trim() ? "Migliora con AI" : "Aiutami a scrivere")}
                  </button>
                  {serviceType && BRIEF_TEMPLATES[serviceType] && !brief && (
                    <button
                      type="button"
                      className="pr-template-btn"
                      onClick={() => setBrief(BRIEF_TEMPLATES[serviceType])}
                    >
                      Usa esempio
                    </button>
                  )}
                </div>
                <div className="pr-brief-r">
                  {tooShort && (
                    <span className="pr-warn">
                      <PR_Icons.info size={12}/> Almeno {briefMin} caratteri
                    </span>
                  )}
                  <span className="pr-count">{brief.length} / 2000</span>
                </div>
              </div>

              {aiOpen && (
                <PRAIPanel
                  loading={aiLoading}
                  error={aiError}
                  suggestion={aiSuggestion}
                  onClose={() => setAiOpen(false)}
                  onAccept={acceptAI}
                  onRetry={askAI}
                />
              )}
            </div>
          </PRSection>

          {/* ============== Allegati ============== */}
          <PRSection num={3} title="Allegati" hint="Reference, demo, voice memo, link YouTube">
            <div className="pr-files">
              <button
                type="button"
                className="pr-upload"
                onClick={() => fileRef.current?.click()}
              >
                <span className="pr-upload-ic"><PR_Icons.upload size={20}/></span>
                <span className="pr-upload-t">Trascina file o clicca per caricare</span>
                <span className="pr-upload-s">MP3 · WAV · PDF · max 25MB · fino a 5 file</span>
              </button>
              <input
                ref={fileRef}
                type="file"
                multiple
                style={{ display: "none" }}
                accept="audio/*,application/pdf,image/*"
                onChange={(e) => onFiles(e.target.files)}
              />

              {files.length > 0 && (
                <ul className="pr-file-list">
                  {files.map(f => (
                    <li key={f.id} className="pr-file">
                      <span className="pr-file-ic">
                        {f.type === "audio" ? <PR_Icons.audioFile size={16}/> :
                         f.type === "image" ? <PR_Icons.target size={16}/> :
                         <PR_Icons.audioFile size={16}/>}
                      </span>
                      <span className="pr-file-body">
                        <span className="pr-file-name">{f.name}</span>
                        <span className="pr-file-meta">{prettyBytes(f.size)} · {f.type}</span>
                      </span>
                      <button
                        type="button"
                        className="pr-file-x"
                        onClick={() => setFiles(prev => prev.filter(x => x.id !== f.id))}
                        aria-label="Rimuovi"
                      >
                        <PR_Icons.close size={14}/>
                      </button>
                    </li>
                  ))}
                </ul>
              )}

              <div className="pr-link-add">
                <PR_Icons.share size={13}/>
                <input
                  type="url"
                  placeholder="…oppure incolla un link YouTube / Drive / Dropbox"
                  className="pr-input pr-link-input"
                />
                <button type="button" className="pr-link-add-btn">Aggiungi</button>
              </div>
            </div>
          </PRSection>

          {/* ============== Budget ============== */}
          <PRSection num={4} title="Budget" hint="Indica un range realistico — i producer offrono di conseguenza">
            <div className="pr-budget">
              <div className="pr-presets">
                {BUDGET_PRESETS.map(b => (
                  <button
                    type="button"
                    key={b.id}
                    className={`pr-chip ${budget === b.id ? "active" : ""}`}
                    onClick={() => {
                      setBudget(b.id);
                      if (b.min !== null) { setBudgetMin(b.min); setBudgetMax(b.max); }
                    }}
                  >
                    {b.id === "open" && <PR_Icons.message size={12}/>}
                    {b.label}
                  </button>
                ))}
              </div>

              {budget !== "open" && (
                <div className="pr-budget-custom">
                  <label className="pr-field">
                    <span className="pr-field-label">Min</span>
                    <span className="pr-input-prefix">
                      <span className="pr-prefix">€</span>
                      <input
                        type="number"
                        className="pr-input pr-input-num"
                        value={budgetMin}
                        min="5"
                        onChange={(e) => setBudgetMin(parseInt(e.target.value || "0", 10))}
                      />
                    </span>
                  </label>
                  <span className="pr-budget-sep">→</span>
                  <label className="pr-field">
                    <span className="pr-field-label">Max</span>
                    <span className="pr-input-prefix">
                      <span className="pr-prefix">€</span>
                      <input
                        type="number"
                        className="pr-input pr-input-num"
                        value={budgetMax}
                        min={budgetMin}
                        onChange={(e) => setBudgetMax(parseInt(e.target.value || "0", 10))}
                      />
                    </span>
                  </label>
                </div>
              )}
            </div>
          </PRSection>

          {/* ============== Deadline ============== */}
          <PRSection num={5} title="Deadline">
            <div className="pr-presets">
              {DEADLINE_PRESETS.map(d => (
                <button
                  type="button"
                  key={d.id}
                  className={`pr-chip ${deadline === d.id ? "active" : ""}`}
                  onClick={() => setDeadline(d.id)}
                >
                  {d.id === "flex" && <PR_Icons.clock size={12}/>}
                  {d.label}
                </button>
              ))}
              <span className="pr-or">oppure</span>
              <label className="pr-field pr-field-inline">
                <input
                  type="date"
                  className="pr-input pr-input-date"
                  value={deadlineDate}
                  onChange={(e) => { setDeadlineDate(e.target.value); setDeadline("custom"); }}
                />
              </label>
            </div>
          </PRSection>

          {/* ============== Visibilità ============== */}
          <PRSection num={6} title="Visibilità">
            <div className="pr-vis">
              <button
                type="button"
                className={`pr-vis-row ${visibility === "public" ? "active" : ""}`}
                onClick={() => setVisibility("public")}
                aria-pressed={visibility === "public"}
              >
                <span className="pr-vis-ic"><PR_Icons.target size={18}/></span>
                <span className="pr-vis-body">
                  <span className="pr-vis-t">Pubblica · consigliata</span>
                  <span className="pr-vis-s">Tutti i producer in linea col tuo profilo possono fare un'offerta. Più offerte, più scelta.</span>
                </span>
                <span className="pr-vis-radio" aria-hidden></span>
              </button>
              <button
                type="button"
                className={`pr-vis-row ${visibility === "invite" ? "active" : ""}`}
                onClick={() => setVisibility("invite")}
                aria-pressed={visibility === "invite"}
              >
                <span className="pr-vis-ic"><PR_Icons.shield size={18}/></span>
                <span className="pr-vis-body">
                  <span className="pr-vis-t">Solo su invito</span>
                  <span className="pr-vis-s">Invii la richiesta solo a producer che scegli tu. Utile se hai già qualcuno in mente.</span>
                </span>
                <span className="pr-vis-radio" aria-hidden></span>
              </button>
            </div>
          </PRSection>

          {/* ============== Mobile submit ============== */}
          <div className="pr-submit-mobile">
            <button type="submit" className="pr-submit-btn" disabled={!canSubmit}>
              Pubblica richiesta <PR_Icons.arrowRight size={14}/>
            </button>
          </div>
        </form>

        {/* ============== Sticky summary ============== */}
        <aside className="pr-summary">
          <div className="pr-summary-card">
            <h3 className="pr-summary-h">Riepilogo</h3>
            <div className="pr-summary-list">
              <PRSummaryRow
                label="Tipo"
                value={selSvc?.label}
                placeholder="Scegli cosa cerchi"
                done={!!serviceType}
              />
              <PRSummaryRow
                label="Brief"
                value={brief.trim() ? `${Math.min(brief.length, 999)} caratteri` : null}
                placeholder="Almeno 40 caratteri"
                done={briefValid}
              />
              <PRSummaryRow
                label="Allegati"
                value={files.length > 0 ? `${files.length} file` : null}
                placeholder="Opzionale"
                muted
                done={files.length > 0}
              />
              <PRSummaryRow
                label="Budget"
                value={selBudg?.id === "open" ? "Da concordare" : `€${budgetMin}–${budgetMax}`}
                done
              />
              <PRSummaryRow
                label="Deadline"
                value={deadline === "custom" && deadlineDate ? formatDate(deadlineDate) : selDdln?.label}
                done
              />
              <PRSummaryRow
                label="Visibilità"
                value={visibility === "public" ? "Pubblica" : "Solo su invito"}
                done
              />
            </div>

            <div className="pr-summary-divider"/>

            <div className="pr-summary-trust">
              <span className="pr-summary-trust-row">
                <PR_Icons.shield size={14}/>
                Pagamento via escrow — paghi solo a lavoro consegnato.
              </span>
              <span className="pr-summary-trust-row">
                <PR_Icons.clock size={14}/>
                La richiesta scade in 30 giorni.
              </span>
            </div>

            <button
              type="submit"
              className="pr-submit-btn"
              disabled={!canSubmit}
              onClick={onSubmit}
            >
              {canSubmit ? <>Pubblica richiesta <PR_Icons.arrowRight size={14}/></> : "Compila i campi obbligatori"}
            </button>

            <p className="pr-summary-note">
              Pubblicando accetti le <a href="#" className="pr-link" onClick={(e) => e.preventDefault()}>linee guida</a>.
              Riceverai le prime offerte tipicamente entro <strong>24h</strong>.
            </p>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ============== Sub-components ============== */

function PRSection({ num, title, required, hint, children }) {
  return (
    <section className="pr-section">
      <header className="pr-section-head">
        <span className="pr-section-num">{num}</span>
        <span className="pr-section-t">
          {title} {required && <span className="pr-req">*</span>}
        </span>
        {hint && <span className="pr-section-hint">{hint}</span>}
      </header>
      <div className="pr-section-body">{children}</div>
    </section>
  );
}

function PRSummaryRow({ label, value, placeholder, done, muted }) {
  return (
    <div className={`pr-sum-row ${done ? "done" : ""} ${muted ? "muted" : ""}`}>
      <span className="pr-sum-label">{label}</span>
      <span className={`pr-sum-value ${value ? "" : "empty"}`}>
        {value || placeholder}
      </span>
    </div>
  );
}

function PRAIPanel({ loading, error, suggestion, onClose, onAccept, onRetry }) {
  return (
    <div className="pr-ai-panel">
      <div className="pr-ai-head">
        <span className="pr-ai-title">
          <PR_Icons.zap size={13}/> Suggerimento AI
        </span>
        <button type="button" className="pr-ai-close" onClick={onClose} aria-label="Chiudi">
          <PR_Icons.close size={14}/>
        </button>
      </div>
      <div className="pr-ai-body">
        {loading && (
          <div className="pr-ai-loading">
            <span className="pr-ai-dot"/><span className="pr-ai-dot"/><span className="pr-ai-dot"/>
            Sto scrivendo per te…
          </div>
        )}
        {error && (
          <div className="pr-ai-error">
            <PR_Icons.info size={14}/> {error}
          </div>
        )}
        {suggestion && !loading && (
          <p className="pr-ai-text">{suggestion}</p>
        )}
      </div>
      {suggestion && !loading && (
        <div className="pr-ai-actions">
          <button type="button" className="pr-ai-secondary" onClick={onRetry}>
            Rigenera
          </button>
          <button type="button" className="pr-ai-primary" onClick={onAccept}>
            <PR_Icons.check size={13}/> Usa questo brief
          </button>
        </div>
      )}
    </div>
  );
}

function PRSuccess({ onNew, type }) {
  return (
    <div className="page pr-success-page">
      <div className="pr-success-card">
        <span className="pr-success-ic">
          <PR_Icons.check size={32}/>
        </span>
        <h1 className="pr-success-t">Richiesta pubblicata</h1>
        <p className="pr-success-s">
          La tua richiesta {type ? <>per <strong>{type}</strong></> : null} è ora visibile ai producer in linea.
          Ti notifichiamo via email e in app appena arriva la prima offerta — di solito entro <strong>24 ore</strong>.
        </p>
        <div className="pr-success-stats">
          <div className="pr-success-stat">
            <span className="pr-success-stat-n">~280</span>
            <span className="pr-success-stat-l">Producer matchati</span>
          </div>
          <div className="pr-success-stat">
            <span className="pr-success-stat-n">~24h</span>
            <span className="pr-success-stat-l">Prima offerta</span>
          </div>
          <div className="pr-success-stat">
            <span className="pr-success-stat-n">30gg</span>
            <span className="pr-success-stat-l">Validità richiesta</span>
          </div>
        </div>
        <div className="pr-success-actions">
          <a href="Progetti.html#richieste" className="pr-submit-btn">
            Vedi le mie richieste <PR_Icons.arrowRight size={14}/>
          </a>
          <button type="button" className="pr-success-secondary" onClick={onNew}>
            Pubblica un'altra
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============== Helpers ============== */

function guessType(f) {
  if (f.type?.startsWith("audio/")) return "audio";
  if (f.type?.startsWith("image/")) return "image";
  if (f.type === "application/pdf") return "pdf";
  return "file";
}
function prettyBytes(n) {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
function formatDate(iso) {
  if (!iso) return "";
  const d = new Date(iso);
  return d.toLocaleDateString("it-IT", { day: "numeric", month: "short", year: "numeric" });
}

Object.assign(window, { PubblicaRichiestaPage });
