// Step 3 — Profile wizard with sub-steps per role
const I3 = window.SonaraIcons;

const GENRES = ["trap","hip-hop","pop","indie","R&B","drill","elettronica","house","rock","cantautorato","jazz","classica","reggaeton","latin","altro"];
const CITIES = ["Milano","Roma","Napoli","Torino","Bologna","Firenze","Palermo","Genova","Bari","Verona"];
const DAWS = ["Ableton","FL Studio","Logic","Pro Tools","Reaper","Cubase","Altro"];
const PRODUCER_SERVICES = ["Beat custom","Beat pronti","Mix","Master","Vocal production","Sound design","Songwriting","Altro"];
const ARTIST_LOOKING = ["Producer","Beat pronti","Mix/Master","Manager","Vocal coach","Altro"];
const MANAGER_AREAS = ["Contratti label","Booking live","Marketing","Distribuzione digitale","A&R","Sync/Licensing","Management 360°","Altro"];
const ROSTER = ["1–3 artisti","4–10 artisti","11–25 artisti","25+ artisti"];

function SubstepStrip({ idx, total }) {
  return (
    <div className="substep-strip">
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={i === idx ? "active" : i < idx ? "done" : ""}/>
      ))}
    </div>
  );
}

function AvatarUploader({ name }) {
  const initial = (name || "?").trim().slice(0, 1).toUpperCase() || "S";
  return (
    <div className="avatar-up">
      <div className="avatar-bubble">{initial}</div>
      <div className="meta">
        <strong>Aggiungi una foto</strong><br/>
        Trascina o <a href="#" style={{ color: "var(--violet-bright,#7b55d0)" }}>scegli un file</a>. JPG/PNG ≤ 5MB.
      </div>
    </div>
  );
}

function NavRow({ onBack, onNext, nextLabel = "Continua", canNext = true, skipLabel }) {
  return (
    <div className="nav-row">
      <button className="btn btn-ghost" onClick={onBack}>Indietro</button>
      <div className="right">
        {skipLabel && <button className="btn btn-ghost" onClick={onNext}>{skipLabel}</button>}
        <button className="btn btn-primary" onClick={onNext} disabled={!canNext}>
          {nextLabel} <I3.arrowRight size={16}/>
        </button>
      </div>
    </div>
  );
}

// === ARTIST ===
function ArtistWizard({ data, setData, onDone, onBack }) {
  const [sub, setSub] = React.useState(0);
  const total = 4;
  const next = () => sub < total - 1 ? setSub(sub + 1) : onDone();
  const back = () => sub === 0 ? onBack() : setSub(sub - 1);

  return (
    <div className="step-enter">
      <SubstepStrip idx={sub} total={total}/>
      <window.Eyebrow>Profilo Artista · {sub + 1}/{total}</window.Eyebrow>

      {sub === 0 && (
        <>
          <h1 className="step-title">Come ti chiami sul palco?</h1>
          <p className="step-subtitle">Il tuo nome d'arte appare in ogni listing, proposta e collaborazione.</p>
          <window.Field label="Nome d'arte" hint="2–40 caratteri. Lo slug del tuo profilo sarà generato in automatico.">
            <input className="input" placeholder="es. Yoshi" value={data.artistName || ""} onChange={(e) => setData({ ...data, artistName: e.target.value })}/>
          </window.Field>
          <window.Field label="Città">
            <input className="input" list="cities" placeholder="Inizia a scrivere..." value={data.city || ""} onChange={(e) => setData({ ...data, city: e.target.value })}/>
            <datalist id="cities">{CITIES.map((c) => <option key={c} value={c}/>)}</datalist>
          </window.Field>
          <NavRow onBack={back} onNext={next} canNext={!!data.artistName && !!data.city}/>
        </>
      )}

      {sub === 1 && (
        <>
          <h1 className="step-title">Che musica fai?</h1>
          <p className="step-subtitle">Scegli da 1 a 3 generi. Servono per matching e discovery.</p>
          <window.Field label={`Generi (${(data.genres || []).length}/3)`}>
            <window.ChipMulti options={GENRES} value={data.genres || []} onChange={(v) => setData({ ...data, genres: v })} max={3}/>
          </window.Field>
          <window.Field label="Cosa cerchi?" optional>
            <window.ChipMulti options={ARTIST_LOOKING} value={data.looking || []} onChange={(v) => setData({ ...data, looking: v })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} canNext={(data.genres || []).length > 0}/>
        </>
      )}

      {sub === 2 && (
        <>
          <h1 className="step-title">Mostrati al meglio.</h1>
          <p className="step-subtitle">Tutto opzionale, ma profili completi ricevono +30% di proposte.</p>
          <AvatarUploader name={data.artistName}/>
          <div style={{ height: 20 }}/>
          <window.Field label="Bio" optional hint="Max 280 caratteri. Diretto, music-first, zero fuffa.">
            <textarea className="input" maxLength={280} placeholder="Cantautrice / trap / Milano. Cerco producer per nuovo EP."
              value={data.bio || ""} onChange={(e) => setData({ ...data, bio: e.target.value })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} skipLabel="Salta"/>
        </>
      )}

      {sub === 3 && (
        <>
          <h1 className="step-title">I tuoi link.</h1>
          <p className="step-subtitle">Aggiungi quello che hai. Ti aiuta a far vedere chi sei.</p>
          <window.Field label="Spotify" optional>
            <input className="input" placeholder="https://open.spotify.com/artist/..." value={data.spotify || ""} onChange={(e) => setData({ ...data, spotify: e.target.value })}/>
          </window.Field>
          <div className="field-row">
            <window.Field label="Instagram" optional>
              <input className="input" placeholder="@tuohandle" value={data.instagram || ""} onChange={(e) => setData({ ...data, instagram: e.target.value })}/>
            </window.Field>
            <window.Field label="SoundCloud" optional>
              <input className="input" placeholder="soundcloud.com/..." value={data.soundcloud || ""} onChange={(e) => setData({ ...data, soundcloud: e.target.value })}/>
            </window.Field>
          </div>
          <div className="field-row">
            <window.Field label="YouTube" optional>
              <input className="input" placeholder="youtube.com/@..." value={data.youtube || ""} onChange={(e) => setData({ ...data, youtube: e.target.value })}/>
            </window.Field>
            <window.Field label="TikTok" optional>
              <input className="input" placeholder="@tuohandle" value={data.tiktok || ""} onChange={(e) => setData({ ...data, tiktok: e.target.value })}/>
            </window.Field>
          </div>
          <NavRow onBack={back} onNext={next} nextLabel="Salva profilo" skipLabel="Salta"/>
        </>
      )}
    </div>
  );
}

// === PRODUCER ===
function ProducerWizard({ data, setData, onDone, onBack }) {
  const [sub, setSub] = React.useState(0);
  const total = 4;
  const next = () => sub < total - 1 ? setSub(sub + 1) : onDone();
  const back = () => sub === 0 ? onBack() : setSub(sub - 1);

  return (
    <div className="step-enter">
      <SubstepStrip idx={sub} total={total}/>
      <window.Eyebrow>Profilo Producer · {sub + 1}/{total}</window.Eyebrow>

      {sub === 0 && (
        <>
          <h1 className="step-title">Come ti chiamano in studio?</h1>
          <p className="step-subtitle">Il tuo alias da producer. È il primo asset del tuo business.</p>
          <window.Field label="Nome producer / alias">
            <input className="input" placeholder="es. Yoshi" value={data.producerName || ""} onChange={(e) => setData({ ...data, producerName: e.target.value })}/>
          </window.Field>
          <window.Field label="Città">
            <input className="input" list="cities" placeholder="Inizia a scrivere..." value={data.city || ""} onChange={(e) => setData({ ...data, city: e.target.value })}/>
          </window.Field>

          <div className="studio-toggle" style={{ marginTop: 18, padding: "14px 16px", borderRadius: 14, border: "1px solid var(--border, rgba(255,255,255,0.12))", background: "rgba(123,85,208,0.05)" }}>
            <window.Checkbox checked={data.hasStudio || false} onChange={(v) => setData({ ...data, hasStudio: v })}>
              <strong>Hai uno studio musicale?</strong>{" "}
              <span style={{ color: "var(--muted-foreground)", fontSize: 13, display: "block", marginTop: 4 }}>
                Se sì, il tuo profilo apparirà anche nella directory studi e potrai ricevere prenotazioni di sessioni.
              </span>
            </window.Checkbox>

            {data.hasStudio && (
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px dashed var(--border, rgba(255,255,255,0.12))", display: "flex", flexDirection: "column", gap: 12 }}>
                <window.Field label="Nome dello studio">
                  <input className="input" placeholder="es. Studio Riva, Lambrate Lab…"
                    value={data.studioName || ""} onChange={(e) => setData({ ...data, studioName: e.target.value })}/>
                </window.Field>

                <div className="field-row">
                  <window.Field label="Indirizzo" hint="Visibile solo dopo conferma prenotazione">
                    <input className="input" placeholder="Via … 12, Milano"
                      value={data.studioAddress || ""} onChange={(e) => setData({ ...data, studioAddress: e.target.value })}/>
                  </window.Field>
                  <window.Field label="Tariffa oraria" optional>
                    <input className="input" type="number" min="0" placeholder="€/h, es. 35"
                      value={data.studioRate || ""} onChange={(e) => setData({ ...data, studioRate: e.target.value })}/>
                  </window.Field>
                </div>

                <window.Field label="Servizi dello studio" optional>
                  <window.ChipMulti
                    options={["Recording", "Mix & Master", "Vocal booth", "Sessions live", "Affitto orario", "Streaming live", "Podcast"]}
                    value={data.studioServices || []}
                    onChange={(v) => setData({ ...data, studioServices: v })}
                  />
                </window.Field>

                <window.Field label="Attrezzatura principale" optional hint="Max 200 caratteri">
                  <textarea className="input" maxLength={200} rows={2}
                    placeholder="Es. SSL Origin, Neumann U87, Pro Tools HDX, mon. Genelec 8351B…"
                    value={data.studioGear || ""} onChange={(e) => setData({ ...data, studioGear: e.target.value })}/>
                </window.Field>
              </div>
            )}
          </div>

          <NavRow onBack={back} onNext={next} canNext={!!data.producerName && !!data.city && (!data.hasStudio || (!!data.studioName && !!data.studioAddress))}/>
        </>
      )}

      {sub === 1 && (
        <>
          <h1 className="step-title">Cosa produci?</h1>
          <p className="step-subtitle">Generi e servizi: ti aiutano ad apparire nei posti giusti.</p>
          <window.Field label={`Generi prodotti (${(data.genres || []).length}/5)`}>
            <window.ChipMulti options={GENRES} value={data.genres || []} onChange={(v) => setData({ ...data, genres: v })} max={5}/>
          </window.Field>
          <window.Field label="Servizi offerti" optional>
            <window.ChipMulti options={PRODUCER_SERVICES} value={data.services || []} onChange={(v) => setData({ ...data, services: v })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} canNext={(data.genres || []).length > 0}/>
        </>
      )}

      {sub === 2 && (
        <>
          <h1 className="step-title">Il tuo setup.</h1>
          <p className="step-subtitle">Niente di tecnico. Aiuta artisti e clienti a trovare match precisi.</p>
          <AvatarUploader name={data.producerName}/>
          <div style={{ height: 20 }}/>
          <div className="field-row">
            <window.Field label="DAW principale" optional>
              <select className="input" value={data.daw || ""} onChange={(e) => setData({ ...data, daw: e.target.value })}>
                <option value="">Seleziona</option>
                {DAWS.map((d) => <option key={d} value={d}>{d}</option>)}
              </select>
            </window.Field>
            <window.Field label="Anni di attività" optional>
              <input className="input" type="number" min="0" max="50" placeholder="0" value={data.years || ""} onChange={(e) => setData({ ...data, years: e.target.value })}/>
            </window.Field>
          </div>
          <window.Field label="Range pricing indicativo" optional>
            <div className="radio-grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
              {[
                { id: "€", t: "€", s: "Entry · sotto 200€" },
                { id: "€€", t: "€€", s: "Mid · 200–800€" },
                { id: "€€€", t: "€€€", s: "Pro · 800€+" },
              ].map((opt) => (
                <div key={opt.id} className={`radio-card ${data.pricing === opt.id ? "selected" : ""}`} onClick={() => setData({ ...data, pricing: opt.id })}>
                  <div className="dot"/>
                  <div className="label-block"><div className="t">{opt.t}</div><div className="s">{opt.s}</div></div>
                </div>
              ))}
            </div>
          </window.Field>
          <NavRow onBack={back} onNext={next} skipLabel="Salta"/>
        </>
      )}

      {sub === 3 && (
        <>
          <h1 className="step-title">Bio e link.</h1>
          <p className="step-subtitle">Il tuo portfolio. Aggiungi quello che mostra la tua qualità.</p>
          <window.Field label="Bio" optional hint="Max 500 caratteri.">
            <textarea className="input" maxLength={500} placeholder="Producer trap/hip-hop con 5 anni di esperienza. Lavoro analogico-digitale, mix incluso."
              value={data.bio || ""} onChange={(e) => setData({ ...data, bio: e.target.value })}/>
          </window.Field>
          <div className="field-row">
            <window.Field label="Spotify" optional>
              <input className="input" placeholder="open.spotify.com/..." value={data.spotify || ""} onChange={(e) => setData({ ...data, spotify: e.target.value })}/>
            </window.Field>
            <window.Field label="SoundCloud" optional>
              <input className="input" placeholder="soundcloud.com/..." value={data.soundcloud || ""} onChange={(e) => setData({ ...data, soundcloud: e.target.value })}/>
            </window.Field>
          </div>
          <div className="field-row">
            <window.Field label="YouTube" optional>
              <input className="input" placeholder="youtube.com/@..." value={data.youtube || ""} onChange={(e) => setData({ ...data, youtube: e.target.value })}/>
            </window.Field>
            <window.Field label="BeatStars" optional>
              <input className="input" placeholder="beatstars.com/..." value={data.beatstars || ""} onChange={(e) => setData({ ...data, beatstars: e.target.value })}/>
            </window.Field>
          </div>
          <NavRow onBack={back} onNext={next} nextLabel="Salva profilo" skipLabel="Salta"/>
        </>
      )}
    </div>
  );
}

// === MANAGER ===
function ManagerWizard({ data, setData, onDone, onBack }) {
  const [sub, setSub] = React.useState(0);
  const total = 4;
  const next = () => sub < total - 1 ? setSub(sub + 1) : onDone();
  const back = () => sub === 0 ? onBack() : setSub(sub - 1);
  const isAgency = data.mgrType === "agency";

  return (
    <div className="step-enter">
      <SubstepStrip idx={sub} total={total}/>
      <window.Eyebrow>Profilo Manager · {sub + 1}/{total}</window.Eyebrow>

      {sub === 0 && (
        <>
          <h1 className="step-title">Come operi?</h1>
          <p className="step-subtitle">Privato o per un'agenzia/etichetta? Scegli per personalizzare il profilo.</p>
          <window.Field label="Tipologia">
            <div className="radio-grid">
              <div className={`radio-card ${data.mgrType === "private" ? "selected" : ""}`} onClick={() => setData({ ...data, mgrType: "private" })}>
                <div className="dot"/>
                <div className="label-block"><div className="t">Privato</div><div className="s">Lavoro in autonomia</div></div>
              </div>
              <div className={`radio-card ${data.mgrType === "agency" ? "selected" : ""}`} onClick={() => setData({ ...data, mgrType: "agency" })}>
                <div className="dot"/>
                <div className="label-block"><div className="t">Agenzia / Etichetta</div><div className="s">Rappresento un'organizzazione</div></div>
              </div>
            </div>
          </window.Field>
          <NavRow onBack={back} onNext={next} canNext={!!data.mgrType}/>
        </>
      )}

      {sub === 1 && (
        <>
          <h1 className="step-title">Le tue info.</h1>
          <p className="step-subtitle">Servono per verificarti. Visibili solo dove serve fiducia.</p>
          <div className="field-row">
            <window.Field label="Nome">
              <input className="input" placeholder="Mario" value={data.firstName || ""} onChange={(e) => setData({ ...data, firstName: e.target.value })}/>
            </window.Field>
            <window.Field label="Cognome">
              <input className="input" placeholder="Rossi" value={data.lastName || ""} onChange={(e) => setData({ ...data, lastName: e.target.value })}/>
            </window.Field>
          </div>
          {isAgency && (
            <window.Field label="Nome agenzia / etichetta">
              <input className="input" placeholder="es. Sound Lab Records" value={data.agency || ""} onChange={(e) => setData({ ...data, agency: e.target.value })}/>
            </window.Field>
          )}
          <window.Field label="Città">
            <input className="input" list="cities" placeholder="Inizia a scrivere..." value={data.city || ""} onChange={(e) => setData({ ...data, city: e.target.value })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} canNext={!!data.firstName && !!data.lastName && !!data.city && (!isAgency || !!data.agency)}/>
        </>
      )}

      {sub === 2 && (
        <>
          <h1 className="step-title">La tua esperienza.</h1>
          <p className="step-subtitle">Aiutaci a posizionarti. Tutto opzionale ma altamente consigliato.</p>
          <AvatarUploader name={data.firstName}/>
          <div style={{ height: 20 }}/>
          <div className="field-row">
            <window.Field label="Anni esperienza" optional>
              <input className="input" type="number" min="0" max="60" placeholder="0" value={data.years || ""} onChange={(e) => setData({ ...data, years: e.target.value })}/>
            </window.Field>
            <window.Field label="Roster attuale" optional>
              <select className="input" value={data.roster || ""} onChange={(e) => setData({ ...data, roster: e.target.value })}>
                <option value="">Seleziona</option>
                {ROSTER.map((r) => <option key={r}>{r}</option>)}
              </select>
            </window.Field>
          </div>
          <window.Field label="Aree di competenza" optional>
            <window.ChipMulti options={MANAGER_AREAS} value={data.areas || []} onChange={(v) => setData({ ...data, areas: v })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} skipLabel="Salta"/>
        </>
      )}

      {sub === 3 && (
        <>
          <h1 className="step-title">Bio e contatti.</h1>
          <p className="step-subtitle">Per artisti che valutano se lavorare con te.</p>
          <window.Field label="Bio professionale" optional hint="Max 500 caratteri.">
            <textarea className="input" maxLength={500} placeholder="15 anni nel music business. Specializzato in artisti hip-hop emergenti. Roster di 8 artisti."
              value={data.bio || ""} onChange={(e) => setData({ ...data, bio: e.target.value })}/>
          </window.Field>
          <div className="field-row">
            <window.Field label="Sito web" optional>
              <input className="input" placeholder="https://..." value={data.website || ""} onChange={(e) => setData({ ...data, website: e.target.value })}/>
            </window.Field>
            <window.Field label="LinkedIn" optional>
              <input className="input" placeholder="linkedin.com/in/..." value={data.linkedin || ""} onChange={(e) => setData({ ...data, linkedin: e.target.value })}/>
            </window.Field>
          </div>
          <window.Field label="Telefono" optional hint="Formato internazionale, es. +39 333 1234567.">
            <input className="input" placeholder="+39 ..." value={data.phone || ""} onChange={(e) => setData({ ...data, phone: e.target.value })}/>
          </window.Field>
          <NavRow onBack={back} onNext={next} nextLabel="Salva profilo" skipLabel="Salta"/>
        </>
      )}
    </div>
  );
}

window.Step3Profile = function Step3Profile({ data, setData, onNext, onBack }) {
  const role = data.role || "artist";
  if (role === "artist") return <ArtistWizard data={data} setData={setData} onDone={onNext} onBack={onBack}/>;
  if (role === "producer") return <ProducerWizard data={data} setData={setData} onDone={onNext} onBack={onBack}/>;
  return <ManagerWizard data={data} setData={setData} onDone={onNext} onBack={onBack}/>;
};
