/* shared-data.jsx — UI helpers, icons, shared components.
   Data comes from the API; mock generators are NOT included. */

const STYLES = [
  "Trash Polka", "Geometrico", "Blackwork", "Neotraditional",
  "Abstract", "Etching", "Fineline", "Realistic", "Old School",
  "Japanese", "Dotwork", "Lettering"
];

const STATUS_LABELS = {
  "da-inviare":   "Da inviare",
  "in-attesa":    "In attesa",
  "lasciata":     "Recensione lasciata",
  "nessuna":      "Nessuna risposta",
  "rifiutata":    "Rifiutata",
  "non-richiesta":"Non richiesta",
};

const RESULT_LABELS = {
  "in-attesa": "In attesa",
  "lasciata":  "Recensione lasciata",
  "nessuna":   "Nessuna risposta",
  "rifiutata": "Rifiutata",
};

const SATISFACTION = {
  "molto":         { label: "Molto soddisfatto", short: "Molto soddisf.", color: "var(--ok)",    bg: "rgba(74, 222, 128, 0.14)" },
  "soddisfatto":   { label: "Soddisfatto",        short: "Soddisfatto",   color: "#a5d96b",      bg: "rgba(165, 217, 107, 0.14)" },
  "neutro":        { label: "Neutro",             short: "Neutro",        color: "var(--warn)",  bg: "rgba(251, 191, 36, 0.14)" },
  "insoddisfatto": { label: "Insoddisfatto",      short: "Insoddisf.",    color: "var(--bad)",   bg: "rgba(248, 113, 113, 0.14)" },
};

const SAT_OPTIONS = ["molto", "soddisfatto", "neutro", "insoddisfatto"];

const MODALITY = {
  "manuale":    { label: "Manuale",    color: "var(--ink-1)", bg: "var(--bg-3)" },
  "automatica": { label: "Automatica", color: "var(--coral)", bg: "var(--coral-soft)" },
};

// ── Helpers ──────────────────────────────────────────────────────────────────

function initials(c) {
  const f = (c.first || "?")[0].toUpperCase();
  const l = (c.last || "")[0] ? c.last[0].toUpperCase() : "";
  return f + l;
}

function fullName(c) { return (c.first + " " + c.last).trim(); }

function methodLabel(m) {
  return { wa: "WhatsApp", mail: "Email", call: "Chiamata" }[m] || m;
}

function fmtDate(d) {
  if (!d) return "—";
  const date = d instanceof Date ? d : new Date(d);
  const today = new Date();
  const diff = Math.floor((today - date) / 86400000);
  if (diff === 0) return "Oggi";
  if (diff === 1) return "Ieri";
  if (diff < 7) return diff + "g fa";
  return date.toLocaleDateString("it-IT", { day: "2-digit", month: "short" });
}

function applyVars(body, c) {
  if (!body) return "";
  return body
    .replace(/\{\{nome\}\}/g,      c ? c.first  : "{{nome}}")
    .replace(/\{\{cognome\}\}/g,   c ? c.last   : "{{cognome}}")
    .replace(/\{\{tatuatore\}\}/g, c ? c.artist : "{{tatuatore}}")
    .replace(/\{\{stile\}\}/g,     c ? (c.style || "") : "{{stile}}");
}

function buildContactURL(client, message) {
  const text = encodeURIComponent(applyVars(message ? message.body : "", client));
  if (client.method === "wa") {
    let digits = client.phone.replace(/\D/g, "");
    // Prepend Italy country code if number is local (≤ 10 digits)
    if (digits.length <= 10) digits = "39" + digits;
    return "https://wa.me/" + digits + (text ? "?text=" + text : "");
  }
  if (client.method === "mail") {
    const subj = encodeURIComponent("Una recensione per MENOUNO? 🖤");
    return "mailto:" + client.email + "?subject=" + subj + (text ? "&body=" + text : "");
  }
  return "tel:" + client.phone.replace(/\s/g, "");
}

async function copyToClipboard(text) {
  try { await navigator.clipboard.writeText(text); return true; } catch { return false; }
}

// ── Icons ─────────────────────────────────────────────────────────────────────

const Icon = ({ name, size = 16 }) => {
  const s = { width: size, height: size, display: "inline-block", flexShrink: 0 };
  const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "wa": return (
      <svg viewBox="0 0 24 24" style={s} fill="currentColor">
        <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.2-.7.2s-.8.9-1 1.1c-.2.2-.4.2-.7.1-.3-.1-1.3-.5-2.5-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.5-.6.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1.1 1.1-1.1 2.6 0 1.5 1.1 3 1.3 3.2.2.2 2.2 3.4 5.3 4.7.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.5-.4z"/>
        <path d="M20.5 3.5A10 10 0 0 0 4.2 16.1L3 21l5-1.3a10 10 0 0 0 15-13a10 10 0 0 0-2.5-3.2zM12 19.4a8.3 8.3 0 0 1-4.2-1.2l-.3-.2-3 .8.8-2.9-.2-.3a8.4 8.4 0 1 1 6.9 3.8z" fillRule="evenodd"/>
      </svg>
    );
    case "mail": return (
      <svg viewBox="0 0 24 24" style={s}>
        <rect x="3" y="5" width="18" height="14" rx="2" {...stroke}/>
        <path d="M3 7l9 6 9-6" {...stroke}/>
      </svg>
    );
    case "call": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M5 4h3l2 5-2.5 1.5a11 11 0 0 0 5 5L14 13l5 2v3a2 2 0 0 1-2 2A14 14 0 0 1 3 6a2 2 0 0 1 2-2z" {...stroke}/>
      </svg>
    );
    case "search": return (
      <svg viewBox="0 0 24 24" style={s}>
        <circle cx="11" cy="11" r="7" {...stroke}/>
        <path d="m20 20-3.5-3.5" {...stroke}/>
      </svg>
    );
    case "send": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M22 2 11 13" {...stroke}/>
        <path d="M22 2l-7 20-4-9-9-4 20-7z" {...stroke}/>
      </svg>
    );
    case "copy": return (
      <svg viewBox="0 0 24 24" style={s}>
        <rect x="9" y="9" width="11" height="11" rx="2" {...stroke}/>
        <path d="M5 15V5a2 2 0 0 1 2-2h10" {...stroke}/>
      </svg>
    );
    case "edit": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M4 20h4l10.5-10.5a2.1 2.1 0 0 0-3-3L5 17v3z" {...stroke}/>
        <path d="M14.5 5.5l3 3" {...stroke}/>
      </svg>
    );
    case "trash": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M4 7h16M9 7V4h6v3M6 7l1 13a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-13" {...stroke}/>
      </svg>
    );
    case "plus": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M12 5v14M5 12h14" {...stroke}/>
      </svg>
    );
    case "check": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="m4 12 5 5L20 6" {...stroke}/>
      </svg>
    );
    case "close": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M6 6l12 12M18 6 6 18" {...stroke}/>
      </svg>
    );
    case "filter": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M3 5h18M6 12h12M10 19h4" {...stroke}/>
      </svg>
    );
    case "star": return (
      <svg viewBox="0 0 24 24" style={s} fill="currentColor">
        <path d="m12 2 3 7h7l-5.5 4.5L18 21l-6-4-6 4 1.5-7.5L2 9h7l3-7z"/>
      </svg>
    );
    case "more": return (
      <svg viewBox="0 0 24 24" style={s}>
        <circle cx="5" cy="12" r="1.5" fill="currentColor"/>
        <circle cx="12" cy="12" r="1.5" fill="currentColor"/>
        <circle cx="19" cy="12" r="1.5" fill="currentColor"/>
      </svg>
    );
    case "chevron": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="m9 6 6 6-6 6" {...stroke}/>
      </svg>
    );
    case "refresh": return (
      <svg viewBox="0 0 24 24" style={s}>
        <path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5" {...stroke}/>
        <path d="M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5" {...stroke}/>
      </svg>
    );
  }
  return null;
};

function MethodIcon({ method, size = 14 }) {
  return <Icon name={method} size={size}/>;
}

// StatusPill: status → pill with dot + label
function StatusPill({ status }) {
  const map = {
    "da-inviare":    ["dainviare",    "Da inviare"],
    "in-attesa":     ["attesa",       "In attesa"],
    "lasciata":      ["lasciata",     "Lasciata"],
    "nessuna":       ["nessuna",      "Nessuna risp."],
    "rifiutata":     ["rifiutata",    "Rifiutata"],
    "non-richiesta": ["nonrichiesta", "Non richiesta"],
  };
  const [cls, label] = map[status] || ["dainviare", status];
  return (
    <span className={"pill " + cls}>
      <span className="dot"></span>
      {label}
    </span>
  );
}

function Stars({ value, max = 5 }) {
  if (!value) return <span style={{ color: "var(--ink-3)", fontSize: 12 }}>—</span>;
  return (
    <span className="stars" title={value + "/" + max + " stelle"}>
      {Array.from({ length: max }).map((_, i) =>
        <span key={i} className={"s " + (i < value ? "on" : "")}>★</span>
      )}
    </span>
  );
}

function StarInput({ value, onChange, size = 15 }) {
  const [hover, setHover] = React.useState(0);
  const shown = hover || value || 0;
  return (
    <span className="stars" onMouseLeave={() => setHover(0)} style={{ cursor: "pointer" }}>
      {[1,2,3,4,5].map(i => (
        <span key={i}
          className={"s " + (i <= shown ? "on" : "")}
          style={{ fontSize: size, padding: "0 1px" }}
          onMouseEnter={() => setHover(i)}
          onClick={e => { e.stopPropagation(); onChange(i); }}
        >★</span>
      ))}
    </span>
  );
}

function SatisfactionSelect({ value, onChange, compact }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const close = e => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, [open]);
  const cfg = value ? SATISFACTION[value] : null;
  return (
    <span className="sat-wrap" ref={ref}>
      <button type="button" className={"sat-pill " + (value || "empty")}
        onClick={e => { e.stopPropagation(); setOpen(o => !o); }}
        style={cfg ? { color: cfg.color, background: cfg.bg, borderColor: "transparent" } : undefined}>
        <span className="sat-dot" style={cfg ? { background: cfg.color } : undefined}></span>
        <span className="sat-text">{cfg ? (compact ? cfg.short : cfg.label) : "— seleziona"}</span>
        <Icon name="chevron" size={11}/>
      </button>
      {open && (
        <div className="sat-menu">
          {SAT_OPTIONS.map(k => {
            const c = SATISFACTION[k];
            return (
              <button key={k} type="button" className="sat-menu-item"
                onClick={e => { e.stopPropagation(); onChange(k); setOpen(false); }}>
                <span className="sat-dot" style={{ background: c.color }}></span>
                <span style={{ color: c.color }}>{c.label}</span>
              </button>
            );
          })}
        </div>
      )}
    </span>
  );
}

function ModalityTag({ value }) {
  if (!value) return <span style={{ color: "var(--ink-3)" }}>—</span>;
  const m = MODALITY[value];
  if (!m) return <span style={{ color: "var(--ink-3)" }}>{value}</span>;
  return <span className="mod-tag" style={{ color: m.color, background: m.bg }}>{m.label}</span>;
}

function PhotoTag({ has }) {
  if (has) return <span className="foto-tag yes">Sì</span>;
  return <span className="foto-tag no">No</span>;
}

function useToast() {
  const [toast, setToast] = React.useState(null);
  const show = React.useCallback(msg => {
    setToast(msg);
    clearTimeout(window.__toastT);
    window.__toastT = setTimeout(() => setToast(null), 2400);
  }, []);
  const node = toast ? (
    <div className="toast">
      <span className="check"><Icon name="check" size={14}/></span>
      {toast}
    </div>
  ) : null;
  return [node, show];
}

Object.assign(window, {
  STATUS_LABELS, RESULT_LABELS, SATISFACTION, SAT_OPTIONS, MODALITY,
  initials, fullName, methodLabel, fmtDate, applyVars, buildContactURL,
  Icon, MethodIcon, StatusPill, Stars, StarInput, SatisfactionSelect,
  ModalityTag, PhotoTag, useToast, copyToClipboard,
});
