const { useState, useEffect, useRef } = React;

// ── Costanti ──────────────────────────────────────────────────────────────────

const REFERRAL_OPT = ["Motore di ricerca","Instagram","Facebook","Passaparola","Rivista online","Fiera del turismo","Altro"];
const MESI_IT      = ["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"];
const GG_IT        = ["Lu","Ma","Me","Gi","Ve","Sa","Do"];

const TYPE_DEFS = [
  { id: "agente",  n: "01", label: "Agente",  sub: "di viaggio",   desc: "Organizzo soggiorni per i miei clienti e cerco partner affidabili in Calabria."           },
  { id: "cliente", n: "02", label: "Cliente", sub: "diretto",      desc: "Sto pianificando un viaggio in Calabria e voglio informazioni e supporto personalizzato." },
  { id: "partner", n: "03", label: "Partner", sub: "editoriale",   desc: "Ho un progetto o un'azienda e voglio collaborare con la rivista Calabria Svelata."        },
  { id: "altro",   n: "04", label: "Altro",   sub: "",             desc: "Ho una domanda o una proposta che non rientra nelle categorie precedenti."                 },
];

// ── Primitivi di form ─────────────────────────────────────────────────────────

function Field({ label, error, children }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 8 }}>{label}</div>
      {children}
      {error && <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ocra)", marginTop: 5, letterSpacing: "0.06em" }}>{error}</div>}
    </div>
  );
}

function TextInput({ value, onChange, placeholder, type = "text", error }) {
  const style = {
    width: "100%", border: "none", outline: "none", background: "transparent",
    borderBottom: `1px solid ${error ? "var(--ocra)" : "var(--line)"}`,
    fontFamily: "var(--font-display)", fontSize: 17, color: "var(--ink)",
    padding: "10px 0", boxSizing: "border-box", transition: "border-color .2s",
  };
  return (
    <input type={type} value={value} placeholder={placeholder || ""} style={style}
      onChange={e => onChange(e.target.value)}
      onFocus={e => { e.target.style.borderBottomColor = "var(--ink)"; }}
      onBlur={e => { e.target.style.borderBottomColor = error ? "var(--ocra)" : "var(--line)"; }}
    />
  );
}

function SelectInput({ value, onChange, options, placeholder, error }) {
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      width: "100%", border: "none", outline: "none", background: "transparent",
      borderBottom: `1px solid ${error ? "var(--ocra)" : "var(--line)"}`,
      fontFamily: "var(--font-display)", fontSize: 17,
      color: value ? "var(--ink)" : "var(--muted)",
      padding: "10px 0", appearance: "none", cursor: "pointer",
      boxSizing: "border-box", transition: "border-color .2s",
    }}>
      <option value="">{placeholder || "Seleziona…"}</option>
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

function TextareaInput({ value, onChange, placeholder, rows = 5, error }) {
  return (
    <textarea value={value} placeholder={placeholder || ""} rows={rows}
      onChange={e => onChange(e.target.value)}
      style={{
        width: "100%", border: "none", outline: "none", background: "transparent",
        borderBottom: `1px solid ${error ? "var(--ocra)" : "var(--line)"}`,
        fontFamily: "var(--font-display)", fontSize: 17, color: "var(--ink)",
        padding: "10px 0", boxSizing: "border-box", resize: "none", transition: "border-color .2s",
      }}
      onFocus={e => { e.target.style.borderBottomColor = "var(--ink)"; }}
      onBlur={e => { e.target.style.borderBottomColor = error ? "var(--ocra)" : "var(--line)"; }}
    />
  );
}

function SubmitBtn({ loading, label }) {
  return (
    <button type="submit" disabled={loading} style={{
      background: loading ? "var(--muted)" : "var(--ink)", color: "var(--paper)",
      border: "none", padding: "16px 52px", fontFamily: "var(--font-mono)",
      fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
      cursor: loading ? "default" : "pointer", transition: "background .25s",
    }}>{loading ? "Invio in corso…" : label}</button>
  );
}

// ── Location autocomplete (Nominatim) ─────────────────────────────────────────

const flagEmoji = cc => cc
  ? [...cc.toUpperCase()].map(c => String.fromCodePoint(c.charCodeAt(0) + 0x1F1A5)).join("")
  : "";

function LocationInput({ value, onChange, error }) {
  const [q, setQ]             = useState(value || "");
  const [flag, setFlag]       = useState("");
  const [results, setResults] = useState([]);
  const [open, setOpen]       = useState(false);
  const [loading, setLoad]    = useState(false);
  const [focused, setFocused] = useState(false);
  const timer  = useRef(null);
  const wrap   = useRef(null);

  useEffect(() => {
    const close = e => { if (wrap.current && !wrap.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const search = val => {
    clearTimeout(timer.current);
    if (val.length < 2) { setResults([]); setOpen(false); return; }
    setLoad(true);
    timer.current = setTimeout(async () => {
      try {
        const r    = await fetch(`https://nominatim.openstreetmap.org/search?format=json&addressdetails=1&q=${encodeURIComponent(val)}&limit=6&accept-language=it`);
        const data = await r.json();
        setResults(data.slice(0, 5));
        setOpen(true);
      } catch {}
      setLoad(false);
    }, 420);
  };

  const pick = item => {
    const a        = item.address;
    const city     = a.city || a.town || a.village || a.county || "";
    const province = a.county || a.state_district || "";
    const state    = a.state || "";
    const country  = a.country || "";
    const label    = [city, province !== city ? province : "", state, country].filter(Boolean).join(", ");
    const fl       = flagEmoji(a.country_code);
    setQ(label);
    setFlag(fl);
    onChange({ label, city, province, state, country, countryCode: a.country_code });
    setOpen(false);
  };

  return (
    <div ref={wrap} style={{ position: "relative" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        borderBottom: `1px solid ${error ? "var(--ocra)" : focused ? "var(--ink)" : "var(--line)"}`,
        transition: "border-color .2s",
      }}>
        {flag && (
          <span style={{ fontSize: 22, lineHeight: 1, flexShrink: 0, userSelect: "none" }}>{flag}</span>
        )}
        <input value={q} placeholder="Es. Milano, Lombardia, Italia" style={{
          flex: 1, border: "none", outline: "none", background: "transparent",
          fontFamily: "var(--font-display)", fontSize: 17, color: "var(--ink)",
          padding: "10px 0", boxSizing: "border-box",
        }}
          onChange={e => { setQ(e.target.value); setFlag(""); onChange(null); search(e.target.value); }}
          onFocus={() => { setFocused(true); if (results.length) setOpen(true); }}
          onBlur={() => setFocused(false)}
        />
        {loading && (
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.2em", flexShrink: 0 }}>···</span>
        )}
      </div>
      {open && results.length > 0 && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, zIndex: 60,
          background: "var(--paper)", border: "1px solid var(--line)",
          boxShadow: "0 12px 40px -8px rgba(0,0,0,.18)",
        }}>
          {results.map((r, i) => {
            const a    = r.address;
            const city = a.city || a.town || a.village || a.county || r.display_name.split(",")[0];
            const sub  = [a.county || a.state_district, a.state, a.country].filter(Boolean).join(", ");
            const fl   = flagEmoji(a.country_code);
            return (
              <button key={i} onMouseDown={() => pick(r)} style={{
                display: "flex", alignItems: "center", gap: 14,
                width: "100%", textAlign: "left",
                padding: "12px 18px", border: "none", background: "transparent",
                borderBottom: i < results.length - 1 ? "1px solid var(--line)" : "none", cursor: "pointer",
              }}
                onMouseEnter={e => e.currentTarget.style.background = "var(--paper-2)"}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <span style={{ fontSize: 24, lineHeight: 1, flexShrink: 0, userSelect: "none" }}>{fl}</span>
                <div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--ink)" }}>{city}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", color: "var(--muted)", marginTop: 2 }}>{sub}</div>
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── Date range picker ─────────────────────────────────────────────────────────

function CalMonthGrid({ year, month, start, end, hovered, onDay, onHover }) {
  const firstDow = new Date(year, month, 1).getDay();
  const offset   = firstDow === 0 ? 6 : firstDow - 1;
  const daysInM  = new Date(year, month + 1, 0).getDate();
  const cells    = Array(offset).fill(null).concat(Array.from({ length: daysInM }, (_, i) => i + 1));
  while (cells.length % 7) cells.push(null);

  const today  = new Date(); today.setHours(0,0,0,0);
  const dt     = d => d ? new Date(year, month, d) : null;
  const same   = (a, b) => a && b && a.getTime() === b.getTime();
  const inRng  = d => {
    if (!d || !start) return false;
    const to = end || hovered;
    if (!to) return false;
    const [lo, hi] = start <= to ? [start, to] : [to, start];
    return dt(d) > lo && dt(d) < hi;
  };

  return (
    <div>
      <div style={{ textAlign: "center", fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500, marginBottom: 18 }}>
        {MESI_IT[month]} {year}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 3 }}>
        {GG_IT.map(d => (
          <div key={d} style={{ textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em", color: "var(--muted)", paddingBottom: 10 }}>{d}</div>
        ))}
        {cells.map((d, i) => {
          const date  = dt(d);
          const isS   = same(date, start);
          const isE   = same(date, end);
          const isSel = isS || isE;
          const isRng = inRng(d);
          const isPst = d && date < today;
          return (
            <div key={i}
              onClick={() => d && !isPst && onDay(date)}
              onMouseEnter={() => d && !isPst && onHover(date)}
              onMouseLeave={() => onHover(null)}
              style={{
                aspectRatio: "1/1", display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 12, fontFamily: "var(--font-mono)", borderRadius: "50%",
                cursor: d && !isPst ? "pointer" : "default",
                color:      !d ? "transparent" : isPst ? "color-mix(in oklab, var(--muted) 50%, transparent)" : isSel ? "var(--paper)" : "var(--ink)",
                background: isSel ? "var(--ink)" : isRng ? "color-mix(in oklab, var(--ocra) 18%, transparent)" : "transparent",
                fontWeight: isSel ? 600 : 400,
                transition: "background .12s",
              }}>{d || ""}</div>
          );
        })}
      </div>
    </div>
  );
}

function DateRangePicker({ value = {}, onChange, error }) {
  const now  = new Date();
  const [vY, setVY]   = useState(now.getFullYear());
  const [vM, setVM]   = useState(now.getMonth());
  const [hover, setHv] = useState(null);
  const [open, setOpen] = useState(false);
  const wrap = useRef(null);

  useEffect(() => {
    const close = e => { if (wrap.current && !wrap.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);

  const m2Y = vM === 11 ? vY + 1 : vY;
  const m2M = (vM + 1) % 12;
  const prev = () => vM === 0  ? (setVY(y => y-1), setVM(11)) : setVM(m => m-1);
  const next = () => vM === 11 ? (setVY(y => y+1), setVM(0))  : setVM(m => m+1);

  const handleDay = date => {
    if (!value.start || (value.start && value.end)) {
      onChange({ start: date, end: null });
    } else {
      if (date < value.start) onChange({ start: date, end: null });
      else { onChange({ start: value.start, end: date }); setOpen(false); }
    }
  };

  const fmt    = d => d ? `${String(d.getDate()).padStart(2,"0")} ${MESI_IT[d.getMonth()].slice(0,3).toUpperCase()} ${d.getFullYear()}` : null;
  const nights = value.start && value.end ? Math.round((value.end - value.start) / 86400000) : null;
  const mobile = useMobile();

  return (
    <div ref={wrap} style={{ position: "relative" }}>
      <div onClick={() => setOpen(v => !v)} style={{
        display: "flex", alignItems: "stretch", cursor: "pointer",
        borderBottom: `1px solid ${error ? "var(--ocra)" : open ? "var(--ink)" : "var(--line)"}`,
        padding: "10px 0 10px", gap: 0, transition: "border-color .2s",
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 4 }}>Partenza</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 16, color: value.start ? "var(--ink)" : "var(--muted)" }}>
            {fmt(value.start) || "— — —"}
          </div>
        </div>
        <div style={{ width: 1, background: "var(--line)", margin: "0 20px" }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 4 }}>Ritorno</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 16, color: value.end ? "var(--ink)" : "var(--muted)" }}>
            {fmt(value.end) || "— — —"}
          </div>
        </div>
        {nights && (
          <div style={{ display: "flex", alignItems: "flex-end", marginLeft: 20, fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", color: "var(--ocra)", paddingBottom: 2 }}>
            {nights} notti
          </div>
        )}
      </div>

      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0, zIndex: 60,
          background: "var(--paper)", border: "1px solid var(--line)",
          boxShadow: "0 20px 60px -12px rgba(0,0,0,.22)", padding: "24px 28px 28px",
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
            <button onClick={e => { e.stopPropagation(); prev(); }} style={{
              border: "1px solid var(--line)", background: "transparent",
              width: 34, height: 34, cursor: "pointer", color: "var(--ink)", fontSize: 18, lineHeight: 1,
            }}>‹</button>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em", color: "var(--muted)" }}>
              {MESI_IT[vM].slice(0,3).toUpperCase()} {vY} &nbsp;—&nbsp; {MESI_IT[m2M].slice(0,3).toUpperCase()} {m2Y}
            </div>
            <button onClick={e => { e.stopPropagation(); next(); }} style={{
              border: "1px solid var(--line)", background: "transparent",
              width: 34, height: 34, cursor: "pointer", color: "var(--ink)", fontSize: 18, lineHeight: 1,
            }}>›</button>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 40 }}>
            <CalMonthGrid year={vY} month={vM} start={value.start} end={value.end} hovered={hover} onDay={handleDay} onHover={setHv} />
            {!mobile && <CalMonthGrid year={m2Y} month={m2M} start={value.start} end={value.end} hovered={hover} onDay={handleDay} onHover={setHv} />}
          </div>

          {value.start && !value.end && (
            <div style={{ marginTop: 20, fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", color: "var(--muted)", textAlign: "center" }}>
              Seleziona la data di ritorno
            </div>
          )}
          {value.start && value.end && (
            <div style={{ marginTop: 20, textAlign: "right" }}>
              <button onClick={() => setOpen(false)} style={{
                background: "var(--ink)", color: "var(--paper)", border: "none",
                padding: "10px 28px", fontFamily: "var(--font-mono)", fontSize: 10,
                letterSpacing: "0.16em", textTransform: "uppercase", cursor: "pointer",
              }}>Conferma</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── Form Agente / Cliente ─────────────────────────────────────────────────────

function AgentClientForm({ onSuccess }) {
  const mobile = useMobile();
  const [f, setF] = useState({ nome:"", cognome:"", email:"", tel:"", luogo:null, date:{}, ref:"" });
  const [err, setErr] = useState({});
  const [busy, setBusy] = useState(false);
  const set = k => v => setF(p => ({ ...p, [k]: v }));

  const validate = () => {
    const e = {};
    if (!f.nome.trim())    e.nome    = "Obbligatorio";
    if (!f.cognome.trim()) e.cognome = "Obbligatorio";
    if (!/\S+@\S+\.\S+/.test(f.email)) e.email = "Email non valida";
    if (!f.luogo?.label)   e.luogo   = "Inserisci una località";
    if (!f.date?.start)    e.date    = "Seleziona le date";
    return e;
  };

  const submit = async e => {
    e.preventDefault();
    const errors = validate();
    if (Object.keys(errors).length) { setErr(errors); return; }
    setBusy(true);
    await new Promise(r => setTimeout(r, 900)); // → sostituire con fetch Formspree / backend
    setBusy(false);
    onSuccess();
  };

  const g2 = { display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: mobile ? 28 : 40 };
  return (
    <form onSubmit={submit} style={{ display: "grid", gap: 36 }}>
      <div style={g2}>
        <Field label="Nome *" error={err.nome}><TextInput value={f.nome} onChange={set("nome")} error={err.nome} /></Field>
        <Field label="Cognome *" error={err.cognome}><TextInput value={f.cognome} onChange={set("cognome")} error={err.cognome} /></Field>
      </div>
      <div style={g2}>
        <Field label="Email *" error={err.email}><TextInput type="email" value={f.email} onChange={set("email")} error={err.email} /></Field>
        <Field label="Telefono"><TextInput type="tel" value={f.tel} onChange={set("tel")} placeholder="+39 …" /></Field>
      </div>
      <Field label="Luogo di provenienza *" error={err.luogo}>
        <LocationInput value={f.luogo?.label} onChange={set("luogo")} error={err.luogo} />
      </Field>
      <Field label="Date del viaggio *" error={err.date}>
        <DateRangePicker value={f.date} onChange={set("date")} error={err.date} />
      </Field>
      <Field label="Come ci hai trovato">
        <SelectInput value={f.ref} onChange={set("ref")} options={REFERRAL_OPT} placeholder="Seleziona…" />
      </Field>
      <div><SubmitBtn loading={busy} label="Invia richiesta" /></div>
    </form>
  );
}

// ── Form Partner ──────────────────────────────────────────────────────────────

function PartnerForm({ onSuccess }) {
  const mobile = useMobile();
  const [f, setF] = useState({ nome:"", cognome:"", email:"", sito:"", social:"", msg:"" });
  const [err, setErr] = useState({});
  const [busy, setBusy] = useState(false);
  const set = k => v => setF(p => ({ ...p, [k]: v }));

  const validate = () => {
    const e = {};
    if (!f.nome.trim())    e.nome    = "Obbligatorio";
    if (!f.cognome.trim()) e.cognome = "Obbligatorio";
    if (!/\S+@\S+\.\S+/.test(f.email)) e.email = "Email non valida";
    if (!f.msg.trim())     e.msg     = "Scrivi un messaggio";
    return e;
  };

  const submit = async e => {
    e.preventDefault();
    const errors = validate();
    if (Object.keys(errors).length) { setErr(errors); return; }
    setBusy(true);
    await new Promise(r => setTimeout(r, 900));
    setBusy(false);
    onSuccess();
  };

  const g2 = { display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: mobile ? 28 : 40 };
  return (
    <form onSubmit={submit} style={{ display: "grid", gap: 36 }}>
      <div style={g2}>
        <Field label="Nome *" error={err.nome}><TextInput value={f.nome} onChange={set("nome")} error={err.nome} /></Field>
        <Field label="Cognome *" error={err.cognome}><TextInput value={f.cognome} onChange={set("cognome")} error={err.cognome} /></Field>
      </div>
      <Field label="Email *" error={err.email}><TextInput type="email" value={f.email} onChange={set("email")} error={err.email} /></Field>
      <div style={g2}>
        <Field label="Sito web"><TextInput value={f.sito} onChange={set("sito")} placeholder="https://…" /></Field>
        <Field label="Social"><TextInput value={f.social} onChange={set("social")} placeholder="@username" /></Field>
      </div>
      <Field label="Messaggio *" error={err.msg}>
        <TextareaInput value={f.msg} onChange={set("msg")} placeholder="Raccontaci il tuo progetto…" error={err.msg} />
      </Field>
      <div><SubmitBtn loading={busy} label="Invia messaggio" /></div>
    </form>
  );
}

// ── Form Altro ────────────────────────────────────────────────────────────────

function AltroForm({ onSuccess }) {
  const mobile = useMobile();
  const [f, setF] = useState({ nome:"", cognome:"", email:"", tel:"", social:"", msg:"" });
  const [err, setErr] = useState({});
  const [busy, setBusy] = useState(false);
  const set = k => v => setF(p => ({ ...p, [k]: v }));

  const validate = () => {
    const e = {};
    if (!f.nome.trim())    e.nome    = "Obbligatorio";
    if (!f.cognome.trim()) e.cognome = "Obbligatorio";
    if (!/\S+@\S+\.\S+/.test(f.email)) e.email = "Email non valida";
    if (!f.msg.trim())     e.msg     = "Scrivi un messaggio";
    return e;
  };

  const submit = async e => {
    e.preventDefault();
    const errors = validate();
    if (Object.keys(errors).length) { setErr(errors); return; }
    setBusy(true);
    await new Promise(r => setTimeout(r, 900));
    setBusy(false);
    onSuccess();
  };

  const g2 = { display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: mobile ? 28 : 40 };
  return (
    <form onSubmit={submit} style={{ display: "grid", gap: 36 }}>
      <div style={g2}>
        <Field label="Nome *" error={err.nome}><TextInput value={f.nome} onChange={set("nome")} error={err.nome} /></Field>
        <Field label="Cognome *" error={err.cognome}><TextInput value={f.cognome} onChange={set("cognome")} error={err.cognome} /></Field>
      </div>
      <div style={g2}>
        <Field label="Email *" error={err.email}><TextInput type="email" value={f.email} onChange={set("email")} error={err.email} /></Field>
        <Field label="Telefono"><TextInput type="tel" value={f.tel} onChange={set("tel")} placeholder="+39 …" /></Field>
      </div>
      <Field label="Social"><TextInput value={f.social} onChange={set("social")} placeholder="@username" /></Field>
      <Field label="Messaggio *" error={err.msg}>
        <TextareaInput value={f.msg} onChange={set("msg")} placeholder="Scrivici…" error={err.msg} />
      </Field>
      <div><SubmitBtn loading={busy} label="Invia messaggio" /></div>
    </form>
  );
}

// ── Card tipo utente ──────────────────────────────────────────────────────────

function TypeCard({ def, selected, onSelect }) {
  const [hover, setHov] = useState(false);
  const active = selected || hover;
  return (
    <button onClick={() => onSelect(def.id)}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{
        textAlign: "left", padding: "28px 24px 24px", border: "1px solid",
        borderColor: selected ? "var(--ink)" : "transparent",
        background: active ? "var(--paper-2)" : "var(--paper)",
        cursor: "pointer", transition: "all .2s",
        display: "flex", flexDirection: "column", gap: 14,
      }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.22em", color: selected ? "var(--ocra)" : "var(--muted)" }}>{def.n}</div>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 30, fontWeight: 500, lineHeight: 1, color: "var(--ink)" }}>{def.label}</div>
        {def.sub && <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 19, color: "var(--muted)", marginTop: 3 }}>{def.sub}</div>}
      </div>
      <p style={{ fontFamily: "var(--font-mono)", fontSize: 11, lineHeight: 1.65, letterSpacing: "0.03em", color: "var(--muted)", margin: 0 }}>{def.desc}</p>
      <div style={{ marginTop: "auto", paddingTop: 16, display: "flex", justifyContent: "flex-end" }}>
        <div style={{
          width: 30, height: 30, borderRadius: 999,
          border: `1px solid ${selected ? "var(--ink)" : "var(--line)"}`,
          background: selected ? "var(--ink)" : "transparent",
          display: "flex", alignItems: "center", justifyContent: "center", transition: "all .2s",
        }}>
          {selected && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--paper)" strokeWidth="2.5"><path d="M5 12l5 5L19 7"/></svg>}
        </div>
      </div>
    </button>
  );
}

// ── Stato di successo ─────────────────────────────────────────────────────────

function SuccessState({ type, onReset }) {
  const msgs = {
    agente:  ["Richiesta ricevuta.", "Ti risponderemo entro 24 ore lavorative con tutti i dettagli del tuo itinerario in Calabria."],
    cliente: ["Grazie per averci scritto.", "Il nostro team ti contatterà presto per aiutarti a pianificare il viaggio perfetto."],
    partner: ["Proposta ricevuta.", "Valuteremo la tua richiesta di collaborazione e ti risponderemo entro 3 giorni lavorativi."],
    altro:   ["Messaggio ricevuto.", "Ti risponderemo al più presto. Grazie per averci contattato."],
  };
  const [title, body] = msgs[type] || msgs.altro;
  return (
    <div style={{ padding: "80px 0", textAlign: "center" }}>
      <div style={{
        width: 60, height: 60, borderRadius: 999, border: "1px solid var(--ocra)",
        display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 36px",
      }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--ocra)" strokeWidth="1.6"><path d="M5 12l5 5L19 7"/></svg>
      </div>
      <h3 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(28px,4vw,52px)", fontWeight: 500, letterSpacing: "-0.015em", margin: "0 0 18px" }}>{title}</h3>
      <p style={{ fontSize: 16, lineHeight: 1.65, color: "var(--muted)", maxWidth: 440, margin: "0 auto 44px" }}>{body}</p>
      <button onClick={onReset} style={{
        border: "1px solid var(--line)", background: "transparent", color: "var(--ink)",
        padding: "12px 28px", fontFamily: "var(--font-mono)", fontSize: 11,
        letterSpacing: "0.16em", textTransform: "uppercase", cursor: "pointer",
      }}>Invia un altro messaggio</button>
    </div>
  );
}

// ── Sezione principale ────────────────────────────────────────────────────────

function ContattiSection() {
  const mobile = useMobile();
  const [type, setType]      = useState(null);
  const [done, setDone]      = useState(false);

  const selectType = t => { setType(t); setDone(false); };

  const renderForm = () => {
    if (!type || done) return null;
    const ok = () => setDone(true);
    if (type === "agente" || type === "cliente") return <AgentClientForm onSuccess={ok} />;
    if (type === "partner") return <PartnerForm onSuccess={ok} />;
    return <AltroForm onSuccess={ok} />;
  };

  return (
    <section id="contatti" style={{ padding: "var(--section-pad) 0", borderTop: "1px solid var(--line)" }}>
      <div className="container">

        {/* ── Intestazione ── */}
        <div style={{ maxWidth: 700, marginBottom: 72 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
            <div style={{ width: 28, height: 1, background: "var(--ocra)" }} />
            <div className="eyebrow">Hai un progetto?</div>
          </div>
          <h2 style={{
            fontFamily: "var(--font-display)", fontSize: "clamp(44px,5.5vw,80px)",
            fontWeight: 500, letterSpacing: "-0.025em", lineHeight: 1.03, margin: "0 0 24px",
          }}>
            Parliamo di<br /><em style={{ fontWeight: 400 }}>Calabria</em>
          </h2>
          <p style={{ fontSize: 17, lineHeight: 1.7, color: "var(--muted)", margin: 0, maxWidth: 500 }}>
            Sei un agente di viaggio, un cliente, un potenziale partner o semplicemente curioso? Scegli chi sei — il modulo si adatta a te.
          </p>
        </div>

        {/* ── Selettore tipo ── */}
        <div style={{ marginBottom: type ? 56 : 80 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 20 }}>
            Chi sei?
          </div>
          <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr 1fr" : "repeat(4, 1fr)", gap: 2, background: "var(--line)" }}>
            {TYPE_DEFS.map(d => (
              <TypeCard key={d.id} def={d} selected={type === d.id} onSelect={selectType} />
            ))}
          </div>
        </div>

        {/* ── Area form ── */}
        {type && (
          done ? (
            <div style={{ maxWidth: 640 }}>
              <SuccessState type={type} onReset={() => { setType(null); setDone(false); }} />
            </div>
          ) : (
            <div style={{
              maxWidth: 680, paddingTop: 48, borderTop: "1px solid var(--line)",
              animation: "rise .35s ease both",
            }}>
              <div style={{
                fontFamily: "var(--font-display)", fontStyle: "italic",
                fontSize: 22, color: "var(--muted)", marginBottom: 52,
              }}>
                {TYPE_DEFS.find(d => d.id === type)?.label}
                {TYPE_DEFS.find(d => d.id === type)?.sub && " " + TYPE_DEFS.find(d => d.id === type)?.sub}
              </div>
              {renderForm()}
            </div>
          )
        )}

        {/* ── Strip info (visibile solo prima di selezionare) ── */}
        {!type && (
          <div style={{
            display: "grid", gridTemplateColumns: mobile ? "1fr" : "repeat(3, 1fr)",
            gap: 40, paddingTop: 72, borderTop: "1px solid var(--line)",
          }}>
            {[
              { label: "Email", val: "ciao@calabriasvelata.it" },
              { label: "Risposta entro", val: "24 – 48 ore lavorative" },
              { label: "Sede", val: "Reggio Calabria, Calabria" },
            ].map(x => (
              <div key={x.label}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 12 }}>{x.label}</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500 }}>{x.val}</div>
              </div>
            ))}
          </div>
        )}

      </div>
    </section>
  );
}
window.ContattiSection = ContattiSection;
