/* ============================================================
   Shared — icons, logo, constants, brief + storage helpers
   Exposed on window for both questionnaire + dashboard apps.
   ============================================================ */

/* ---- Icon set (stroke, 1.6) ---- */
/* Order prefill (onboarding, 7-nov-2026). After paying on arigatovideos.com the client lands here with
   ?order=ARI-1002 and their name, email and company after the #. They seed this page's draft before the app reads it,
   the order number goes out with the answers, and the # part leaves the address bar right away. */
const ARIGATO_ORDER = (() => {
  const DRAFTS = {
    "/greeting-card": "arigato_greeting_card_draft", "/explainer": "arigato_explainer_draft",
    "/logo-animation": "arigato_logo_animation_draft", "/lottie": "arigato_lottie_draft",
    "/email-signature": "arigato_email_signature_draft", "/music-video": "arigato_music_video_draft",
  };
  const path = location.pathname.replace(/\.html$/, "").replace(/\/$/, "");
  let order = "";
  try {
    const fromUrl = new URLSearchParams(location.search).get("order") || "";
    if (/^(ARI|TEST)-\d{4,6}$/.test(fromUrl)) {
      order = fromUrl;
      sessionStorage.setItem("arigato_order", JSON.stringify({ order, path }));
    } else {
      const kept = JSON.parse(sessionStorage.getItem("arigato_order") || "null");
      if (kept && kept.path === path) order = kept.order || "";
    }
    const h = new URLSearchParams(location.hash.slice(1));
    const seed = { email: h.get("email") || "", clientName: h.get("name") || "", brandName: h.get("company") || "" };
    if (location.hash) history.replaceState(null, "", location.pathname + location.search);
    const key = DRAFTS[path];
    if (key && (seed.email || seed.clientName || seed.brandName)) {
      const draft = JSON.parse(sessionStorage.getItem(key) || "null") || {};
      for (const [k, v] of Object.entries(seed)) if (v && !draft[k]) draft[k] = v.slice(0, 200);
      sessionStorage.setItem(key, JSON.stringify(draft));
    }
  } catch {}
  return order;
})();

function Icon({ name, size = 18, stroke = 1.6, ...rest }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round", ...rest };
  const paths = {
    check: <polyline points="4 12 9 17 20 6" />,
    "chevron-left": <polyline points="15 5 8 12 15 19" />,
    "chevron-right": <polyline points="9 5 16 12 9 19" />,
    x: <g><line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" /></g>,
    plus: <g><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></g>,
    upload: <g><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" /><polyline points="8 9 12 5 16 9" /><line x1="12" y1="5" x2="12" y2="16" /></g>,
    download: <g><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" /><polyline points="8 12 12 16 16 12" /><line x1="12" y1="4" x2="12" y2="16" /></g>,
    copy: <g><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h8" /></g>,
    send: <g><line x1="20" y1="4" x2="9" y2="15" /><polygon points="20 4 14 20 11 13 4 10 20 4" /></g>,
    edit: <g><path d="M12 20h8" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" /></g>,
    search: <g><circle cx="11" cy="11" r="7" /><line x1="21" y1="21" x2="16.5" y2="16.5" /></g>,
    file: <g><path d="M14 3v5h5" /><path d="M19 8v11a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h8Z" /></g>,
    image: <g><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="9" cy="10" r="2" /><path d="m4 18 5-5 4 4 3-3 4 4" /></g>,
    link: <g><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1" /><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1" /></g>,
    eye: <g><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></g>,
    "alert": <g><circle cx="12" cy="12" r="9" /><line x1="12" y1="7" x2="12" y2="13" /><line x1="12" y1="16.5" x2="12" y2="16.6" /></g>,
    "arrow-right": <g><line x1="5" y1="12" x2="19" y2="12" /><polyline points="13 6 19 12 13 18" /></g>,
    "arrow-left": <g><line x1="19" y1="12" x2="5" y2="12" /><polyline points="11 6 5 12 11 18" /></g>,
    clock: <g><circle cx="12" cy="12" r="9" /><polyline points="12 7 12 12 15 14" /></g>,
    archive: <g><rect x="3" y="4" width="18" height="4" rx="1" /><path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8" /><line x1="10" y1="12" x2="14" y2="12" /></g>,
    sliders: <g><line x1="4" y1="8" x2="20" y2="8" /><circle cx="9" cy="8" r="2.4" fill="var(--paper)" /><line x1="4" y1="16" x2="20" y2="16" /><circle cx="15" cy="16" r="2.4" fill="var(--paper)" /></g>,
    grid: <g><rect x="4" y="4" width="7" height="7" rx="1" /><rect x="13" y="4" width="7" height="7" rx="1" /><rect x="4" y="13" width="7" height="7" rx="1" /><rect x="13" y="13" width="7" height="7" rx="1" /></g>,
    list: <g><line x1="8" y1="6" x2="20" y2="6" /><line x1="8" y1="12" x2="20" y2="12" /><line x1="8" y1="18" x2="20" y2="18" /><circle cx="4" cy="6" r="1" /><circle cx="4" cy="12" r="1" /><circle cx="4" cy="18" r="1" /></g>,
    inbox: <g><path d="M3 12h5l2 3h4l2-3h5" /><path d="M5 5h14l2 7v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-6Z" /></g>,
    note: <g><path d="M5 4h14a1 1 0 0 1 1 1v9l-5 5H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z" /><path d="M20 14h-5v5" /></g>,
    external: <g><path d="M14 4h6v6" /><line x1="20" y1="4" x2="11" y2="13" /><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" /></g>,
  };
  return <svg {...p}>{paths[name] || null}</svg>;
}

/* ---- Logo lockup ---- */
function Logo({ size = 34 }) {
  return (
    <a className="brand" href="/">
      <img className="brand-mark-img" src="assets/arigato-studio-logo.png" width={size} height={size} alt="" />
      <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
        <span className="brand-name">ARIGATO</span>
        <span className="brand-sub">studio · questionnaires</span>
      </span>
    </a>
  );
}

/* ---- Option constants ---- */
const LOGO_STYLES = [
  { id: "text", name: "Text only", glyph: "Aa" },
  { id: "icon-text", name: "Icon + text", glyph: "icon" },
  { id: "monogram", name: "Initials / monogram", glyph: "AB" },
  { id: "emblem", name: "Badge / emblem", glyph: "emblem" },
  { id: "illustrated", name: "Illustrated", glyph: "illus" },
  { id: "mascot", name: "Mascot", glyph: "mascot" },
  { id: "minimal", name: "Minimal", glyph: "minimal" },
  { id: "luxury", name: "Luxury", glyph: "luxury" },
  { id: "corporate", name: "Corporate", glyph: "corp" },
  { id: "unsure", name: "Not sure yet", glyph: "?" },
];
const FEELINGS = ["Professional","Modern","Luxury","Friendly","Elegant","Bold","Clean","Creative","Trustworthy","Playful","Premium","Simple"];
const CONCEPT_OPTIONS = [
  { id: "clear", title: "Yes, I have a clear idea", desc: "I know the symbol or concept I want." },
  { id: "rough", title: "I have a rough idea", desc: "A loose direction the designer can shape." },
  { id: "open", title: "I want the designer to suggest", desc: "Open to concepts and exploration." },
];
const TYPO_STYLES = ["Modern","Elegant","Bold","Simple","Luxury","Friendly","Classic","Serious","Creative","Not sure"];
const USAGE_OPTIONS = [
  "Website","Social media","Profile picture","Business cards","Packaging","Uniforms",
  "Print materials","App icon","Email signature","Vehicle or storefront",
  "White background version","Transparent background version","Square version","Horizontal version","Icon only version",
];

const QUESTIONNAIRE_TYPES = {
  "greeting-card": { label: "Animated greeting card", briefLabel: "ANIMATED GREETING CARD BRIEF", description: "Holiday, celebration and thank you animations." },
  "social-content-editing": { label: "Social media content editing", briefLabel: "SOCIAL MEDIA CONTENT EDITING BRIEF", description: "Visual identity and recurring social video editing." },
  "logo-design": {
    label: "Logo design",
    briefLabel: "LOGO DESIGN BRIEF",
    description: "New logo and brand mark projects.",
  },
  "logo-animation": {
    label: "Logo animation",
    briefLabel: "LOGO ANIMATION BRIEF",
    description: "Motion, reveal, intro and loop projects using an existing logo.",
  },
  "explainer": { label: "Explainer video", briefLabel: "EXPLAINER VIDEO BRIEF", description: "Coming soon." },
  "lottie": { label: "Lottie animation", briefLabel: "LOTTIE ANIMATION BRIEF", description: "Lightweight web and app animations." },
  "email-signature": {
    label: "Email signature",
    briefLabel: "EMAIL SIGNATURE BRIEF",
    description: "HTML/GIF email signature projects.",
  },
  "music-video": { label: "Music video", briefLabel: "MUSIC VIDEO BRIEF", description: "Lyric, animated and kids music video projects." },
  "ai-diagnosis": {
    label: "AI automation diagnosis",
    briefLabel: "AI AUTOMATION DIAGNOSIS",
    description: "Intake for the paid diagnosis: operations, tools, data and priorities.",
  },
};

function getQuestionnaireMeta(type) {
  return QUESTIONNAIRE_TYPES[type] || { label: type || "Questionnaire", briefLabel: "PROJECT BRIEF", description: "" };
}

const LOGO_ANIMATION_TYPES = [
  "Clean logo reveal",
  "Draw-on / line animation",
  "Icon-to-wordmark reveal",
  "Dynamic intro",
  "Minimal loop",
  "Premium / cinematic",
  "Playful motion",
  "Morphing / transformation",
  "Not sure yet",
];
const ANIMATION_FEELINGS = ["Professional","Modern","Elegant","Energetic","Bold","Clean","Premium","Friendly","Playful","Tech","Luxury","Simple"];
const ANIMATION_USAGE = [
  "YouTube intro or outro","Social media","Website","Presentation","App or product UI",
  "Paid ads","Event screen","Email signature","Video watermark","Other",
];
const ANIMATION_FORMATS = [
  "MP4","MOV with transparent background","GIF","Lottie","Square version","Horizontal version",
  "Vertical version","Source files","Not sure yet",
];
const ANIMATION_DURATIONS = ["2–3 seconds","4–5 seconds","6–8 seconds","9–12 seconds","Looping animation","Not sure yet"];
const AUDIO_OPTIONS = ["No audio","Sound effects only","Background music only","Sound effects + music","Not sure yet"];

/* ---- Style glyph renderer (tiny abstract previews) ---- */
function StyleGlyph({ kind }) {
  const c = "#384259", coral = "#E13F5B", cyan = "#82FFFA";
  const wrap = (children) => <svg width="64" height="34" viewBox="0 0 64 34">{children}</svg>;
  switch (kind) {
    case "Aa": return <span style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 20, letterSpacing: "-0.02em" }}>Studio</span>;
    case "AB": return <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontWeight: 600, fontSize: 22 }}>AB</span>;
    case "?": return <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 22, color: "var(--navy-400)" }}>?</span>;
    case "icon": return wrap(<g><circle cx="16" cy="17" r="9" fill="none" stroke={coral} strokeWidth="2.5" /><rect x="31" y="13" width="22" height="3.4" rx="1.7" fill={c} /><rect x="31" y="19" width="14" height="3.4" rx="1.7" fill="#97A0B8" /></g>);
    case "emblem": return wrap(<g><circle cx="32" cy="17" r="13" fill="none" stroke={c} strokeWidth="2" /><circle cx="32" cy="17" r="8.5" fill="none" stroke={coral} strokeWidth="1.4" /><rect x="27" y="15" width="10" height="4" rx="1" fill={c} /></g>);
    case "minimal": return wrap(<g><line x1="22" y1="17" x2="42" y2="17" stroke={c} strokeWidth="2.4" strokeLinecap="round" /><circle cx="32" cy="17" r="3.2" fill={coral} /></g>);
    case "luxury": return wrap(<g><path d="M32 6 L36 15 L32 24 L28 15 Z" fill="none" stroke={c} strokeWidth="1.6" /><line x1="20" y1="28" x2="44" y2="28" stroke={coral} strokeWidth="1.4" /></g>);
    case "corp": return wrap(<g><rect x="20" y="9" width="7" height="16" rx="1.5" fill={c} /><rect x="29" y="13" width="7" height="12" rx="1.5" fill="#97A0B8" /><rect x="38" y="6" width="7" height="19" rx="1.5" fill={coral} /></g>);
    case "illus": return wrap(<g><path d="M18 24 Q24 8 32 16 Q40 24 46 12" fill="none" stroke={c} strokeWidth="2" /><circle cx="46" cy="12" r="3" fill={cyan} stroke={c} strokeWidth="1.2" /></g>);
    case "mascot": return wrap(<g><circle cx="32" cy="16" r="10" fill="none" stroke={c} strokeWidth="2" /><circle cx="28" cy="14" r="1.8" fill={c} /><circle cx="36" cy="14" r="1.8" fill={c} /><path d="M28 20 Q32 23 36 20" fill="none" stroke={coral} strokeWidth="1.6" /></g>);
    default: return null;
  }
}

/* ---- Empty default answers ---- */
function emptyAnswers() {
  return {
    questionnaireType: "logo-design",
    brandName: "", slogan: "", description: "", audience: "",
    styles: [], feelings: [],
    refFiles: [], refLinks: [""], refNotes: "",
    concept: "", conceptDetail: "", avoidElements: "",
    colorsLike: "", colorsAvoid: "", typography: [],
    usage: [], sizes: "",
  };
}

function emptyLogoAnimationAnswers() {
  return {
    questionnaireType: "logo-animation",
    clientName: "", email: "",
    brandName: "", website: "", description: "",
    logoFiles: [], logoLinks: [""], logoNotes: "",
    animationTypes: [], animationFeelings: [],
    refFiles: [], refLinks: [""], refNotes: "",
    logoMeaning: "", animationIdea: "", includeElements: "", avoidElements: "",
    audio: "", usage: [], duration: "", formats: [], sizes: "", deadline: "",
  };
}

/* ---- Brief assembly (label/value pairs) ---- */
function cleanList(list) {
  return (Array.isArray(list) ? list : []).filter(Boolean);
}
function buildBriefSections(a, questionnaireType = a?.questionnaireType || "logo-design") {
  a = a || {};
  if (questionnaireType === "social-content-editing" && a.questionnaireVariant === "visual-style") {
    return [
      { key: "Client", value: a.clientName || "", kind: "text" },
      { key: "Email", value: a.email || "", kind: "text" },
      { key: "Brand / account", value: a.brandName || "", kind: "text" },
      { key: "Account links", value: a.profileLinks || "", kind: "text" },
      { key: "Audience and priorities", value: a.audience || "", kind: "text" },
      { key: "Video references and what you like", value: { notes: a.styleReferences || "", files: cleanList(a.refFiles) }, kind: "refs" },
      { key: "Desired look and feel", value: a.visualStyleNotes || "", kind: "text" },
      { key: "Editing pace and on camera delivery", value: a.editingPace || "", kind: "text" },
      { key: "Captions, graphics and brand guidelines", value: { notes: a.graphicPreferences || "", files: cleanList(a.logoFiles) }, kind: "refs" },
      { key: "Music and sound", value: { notes: a.soundPreferences || "", files: cleanList(a.assetFiles) }, kind: "refs" },
      { key: "Styles and effects to avoid", value: { notes: a.styleAvoidances || "", files: cleanList(a.extraFiles) }, kind: "refs" },
    ];
  }
  if (questionnaireType === "social-content-editing") {
    return [
      { key: "Client", value: a.clientName || "", kind: "text" },
      { key: "Email", value: a.email || "", kind: "text" },
      { key: "Brand / account", value: a.brandName || "", kind: "text" },
      { key: "Account links", value: a.profileLinks || "", kind: "text" },
      { key: "Audience and priorities", value: a.audience || "", kind: "text" },
      { key: "A real example of your value", value: a.valueExample || "", kind: "text" },
      { key: "Visual direction and brand guidelines", value: a.visualStyleNotes || "", kind: "text" },
      { key: "First video idea", value: a.firstVideo || "", kind: "text" },
      { key: "Material and restrictions", value: a.materialNotes || "", kind: "text" },
      { key: "Viewer action", value: a.callToAction || "", kind: "text" },
      { key: "Approval contact and timing", value: a.approvalNotes || "", kind: "text" },
    ];
  }
  if (questionnaireType === "logo-animation") {
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Brand / company", value: a.brandName || "—", kind: "text" },
      { key: "Website", value: a.website || "—", kind: "text" },
      { key: "Business description", value: a.description || "—", kind: "text" },
      { key: "Logo files & brand guidelines", value: { links: cleanList(a.logoLinks), files: cleanList(a.logoFiles), notes: a.logoNotes }, kind: "refs" },
      { key: "Animation style", value: cleanList(a.animationTypes), kind: "tags" },
      { key: "Animation feeling", value: cleanList(a.animationFeelings), kind: "tags-coral" },
      { key: "References", value: { links: cleanList(a.refLinks), files: cleanList(a.refFiles), notes: a.refNotes }, kind: "refs" },
      { key: "Logo meaning", value: a.logoMeaning || "—", kind: "text" },
      { key: "Creative idea", value: a.animationIdea || "—", kind: "text" },
      { key: "Elements to include", value: a.includeElements || "—", kind: "text" },
      { key: "Elements to avoid", value: a.avoidElements || "—", kind: "text" },
      { key: "Audio", value: a.audio || "—", kind: "text" },
      { key: "Usage", value: cleanList(a.usage), kind: "tags" },
      { key: "Duration", value: a.duration || "—", kind: "text" },
      { key: "Formats & versions", value: { versions: cleanList(a.formats), sizes: a.sizes }, kind: "versions" },
      { key: "Deadline / notes", value: a.deadline || "—", kind: "text" },
    ];
  }
  if (questionnaireType === "ai-diagnosis") {
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Business", value: a.brandName || "—", kind: "text" },
      { key: "Website", value: a.website || "—", kind: "text" },
      { key: "What the business sells", value: a.description || "—", kind: "text" },
      { key: "Team size", value: a.teamSize || "—", kind: "text" },
      { key: "Sales channels", value: cleanList(a.channels), kind: "tags" },
      { key: "Daily tools", value: cleanList([...(Array.isArray(a.tools) ? a.tools : []), a.toolsOther]), kind: "tags" },
      { key: "Admin access", value: a.adminAccess || "—", kind: "text" },
      { key: "Most repetitive task", value: a.repetitiveTask || "—", kind: "text" },
      { key: "Hours per week on it", value: a.hoursPerWeek || "—", kind: "text" },
      { key: "Who does it", value: a.whoDoesIt || "—", kind: "text" },
      { key: "What they'd do instead", value: a.freedTime || "—", kind: "text" },
      { key: "Monthly volume", value: [a.monthlyVolume, a.volumeUnit].filter(Boolean).join(" — ") || "—", kind: "text" },
      { key: "Customer list", value: a.customerList || "—", kind: "text" },
      { key: "Where the list lives", value: a.listLocation || "—", kind: "text" },
      { key: "Where money leaks", value: cleanList(a.leaks), kind: "tags-coral" },
      { key: "Leak detail", value: a.leakDetail || "—", kind: "text" },
      { key: "Tried automating before", value: a.triedBefore || "—", kind: "text" },
      { key: "What happened", value: a.triedDetail || "—", kind: "text" },
      { key: "90-day priority", value: a.ninetyDayGoal || "—", kind: "text" },
      { key: "Constraints", value: a.constraints || "—", kind: "text" },
      { key: "Attachments", value: { links: [], files: cleanList(a.extraFiles), notes: "" }, kind: "refs" },
      { key: "Extra notes", value: a.notes || "—", kind: "text" },
    ];
  }
  if (questionnaireType === "explainer") {
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Brand / company", value: a.brandName || "—", kind: "text" },
      { key: "Website", value: a.website || "—", kind: "text" },
      { key: "Business / product", value: a.description || "—", kind: "text" },
      { key: "Brand assets", value: { links: [], files: cleanList(a.logoFiles), notes: "" }, kind: "refs" },
      { key: "Target audience", value: a.audience || "—", kind: "text" },
      { key: "Audience problem", value: a.problem || "—", kind: "text" },
      { key: "Solution", value: a.solution || "—", kind: "text" },
      { key: "Differentiator", value: a.differentiator || "—", kind: "text" },
      { key: "Video goal", value: a.goal || "—", kind: "text" },
      { key: "Core message", value: a.coreMessage || "—", kind: "text" },
      { key: "Call to action", value: a.callToAction || "—", kind: "text" },
      { key: "Script / voiceover", value: { links: [], files: cleanList(a.scriptFiles), notes: a.scriptText }, kind: "refs" },
      { key: "Preferred video style", value: a.videoStyle || "—", kind: "text" },
      { key: "Tone / mood", value: cleanList(a.tone), kind: "tags-coral" },
      { key: "Serious vs fun", value: a.funLevel || "—", kind: "text" },
      { key: "References", value: { links: cleanList(a.refLinks), files: [], notes: a.refNotes }, kind: "refs" },
      { key: "Preferred duration", value: a.duration || "—", kind: "text" },
      { key: "Colors", value: { like: a.colorsLike, avoid: a.colorsAvoid }, kind: "colors" },
      { key: "Usage / platforms", value: cleanList(a.usage), kind: "tags" },
      { key: "Deadline / notes", value: a.deadline || "—", kind: "text" },
    ];
  }
  if (questionnaireType === "lottie") {
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Brand / company", value: a.brandName || "—", kind: "text" },
      { key: "Website", value: a.website || "—", kind: "text" },
      { key: "Business / product", value: a.description || "—", kind: "text" },
      { key: "Assets", value: { links: [], files: cleanList(a.assetFiles), notes: "" }, kind: "refs" },
      { key: "Animation purpose", value: a.animationPurpose || "—", kind: "text" },
      { key: "Where it will be used", value: cleanList(a.platforms), kind: "tags" },
      { key: "What should happen", value: a.animationDescription || "—", kind: "text" },
      { key: "Tone / mood", value: cleanList(a.mood), kind: "tags-coral" },
      { key: "References", value: { links: cleanList(a.refLinks), files: [], notes: a.refNotes }, kind: "refs" },
      { key: "Elements to include", value: a.includeElements || "—", kind: "text" },
      { key: "Elements to avoid", value: a.avoidElements || "—", kind: "text" },
      { key: "Loop / interaction", value: [a.loopBehavior, a.interaction].filter(Boolean).join(" · ") || "—", kind: "text" },
      { key: "Duration", value: a.duration || "—", kind: "text" },
      { key: "Background", value: a.background || "—", kind: "text" },
      { key: "Formats", value: cleanList(a.formats), kind: "tags" },
      { key: "Dimensions / technical notes", value: a.dimensions || "—", kind: "text" },
      { key: "Deadline / notes", value: a.deadline || "—", kind: "text" },
    ];
  }
  if (questionnaireType === "greeting-card" && a.collectionVariant === "mytassel-eight-cards") {
    const labels={clientName:"Client / Fiverr username",brandName:"Brand",collectionScope:"Confirmed collection",occasionAudience:"Graduation audience",collectionStyle:"Style across the collection",designNotes:"Brand, logo, colors and details",referenceNotes:"Notes on the references",assetLink:"Additional brand materials",playback:"Playback",textlessUse:"Version without text",audioPreference:"Sound preference",targetDate:"Preferred launch date",deliveryNotes:"Additional requirements"};
    return [...Object.entries(labels).map(([field,key])=>({key,value:a[field]||"",kind:"text"})),...Array.from({length:8},(_,i)=>({key:`Card ${i+1} idea`,value:a[`card${i+1}Brief`]||"",kind:"text"}))];
  }
  if (questionnaireType === "greeting-card") {
    return [
      { key: "Client", value: a.clientName || "", kind: "text" },
      { key: "Email", value: a.email || "", kind: "text" },
      { key: "Company / brand", value: a.brandName || "", kind: "text" },
      { key: "Logo and brand materials", value: a.assetStatus || "", kind: "text" },
      { key: "Asset folder", value: a.assetLink || "", kind: "text" },
      { key: "Occasion and audience", value: a.occasionAudience || "", kind: "text" },
      { key: "Message readiness", value: a.messageStatus || "", kind: "text" },
      { key: "Greeting message", value: a.greetingMessage || "", kind: "text" },
      { key: "Language", value: a.language || "", kind: "text" },
      { key: "Scene and animation idea", value: a.visualIdea || "", kind: "text" },
      { key: "Colors, details and things to avoid", value: a.designNotes || "", kind: "text" },
      { key: "References", value: a.referenceNotes || "", kind: "text" },
      { key: "Where it will be used", value: a.usage || "", kind: "text" },
      { key: "Email platform and support", value: a.emailSetup || "", kind: "text" },
      { key: "Individual versions", value: a.personalization || "", kind: "text" },
      { key: "Estimated recipients", value: a.recipientCount || "", kind: "text" },
      { key: "Other changes and available materials", value: a.personalizationNotes || "", kind: "text" },
      { key: "Link to video or page", value: a.videoLink || "", kind: "text" },
      { key: "Video / destination details", value: a.videoDetails || "", kind: "text" },
      { key: "Preferred send or launch date", value: a.targetDate || "", kind: "text" },
      { key: "Additional requirements", value: a.deliveryNotes || "", kind: "text" },
      { key: "Look and feel", value: cleanList(a.styleMood), kind: "tags-coral" },
      { key: "Logo and reference files", value: { links: [], files: cleanList(a.logoFiles), notes: "" }, kind: "refs" },
    ];
  }
  if (questionnaireType === "email-signature") {
    const legacySignatureContent = [
      a.signatureName,
      a.signatureTitle,
      a.signatureCompany,
      a.signatureEmail,
      a.phone,
      a.mobile,
      a.address,
      a.extraContactDetails,
    ].filter(Boolean).join("\n");
    const signatureContent = a.signatureContent || legacySignatureContent || "—";
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Brand / company", value: a.brandName || "—", kind: "text" },
      { key: "Website", value: a.website || "—", kind: "text" },
      { key: "Brand description", value: a.description || "—", kind: "text" },
      { key: "Logo preference", value: a.includeLogo || "—", kind: "text" },
      { key: "Logo / brand assets", value: { links: [], files: cleanList(a.logoFiles), notes: "" }, kind: "refs" },
      { key: "Signature content", value: signatureContent, kind: "text" },
      { key: "Profile photo", value: { links: [], files: cleanList(a.photoFiles), notes: a.includePhoto }, kind: "refs" },
      { key: "Links and socials", value: [a.websiteLink, a.instagram, a.linkedin, a.facebook, a.youtube, a.tiktok, a.whatsapp, a.bookingLink, a.otherLinks].filter(Boolean).join("\n") || "—", kind: "text" },
      { key: "Style / mood", value: cleanList(a.styleMood), kind: "tags-coral" },
      { key: "Colors", value: { like: a.colorsLike, avoid: a.colorsAvoid }, kind: "colors" },
      { key: "Animation", value: [a.animationTarget, a.animationStyle].filter(Boolean).join(" · ") || "—", kind: "text" },
      { key: "References", value: { links: cleanList(a.refLinks), files: [], notes: a.refNotes }, kind: "refs" },
      { key: "Email apps", value: (a.emailProviders || []).join(", ") || a.emailProvider || "—", kind: "text" },
      { key: "Users / team rollout", value: a.teamDetails || "—", kind: "text" },
      { key: "Main button text", value: a.ctaLabel || "—", kind: "text" },
      { key: "Main button URL", value: a.ctaUrl || "—", kind: "text" },
      { key: "Email setup requirements", value: a.emailClientDetails || "—", kind: "text" },
      { key: "Installation / updates", value: a.installationMethod || "—", kind: "text" },
      { key: "Image hosting", value: a.imageHosting || "—", kind: "text" },
      { key: "Preferred output", value: cleanList(a.formats), kind: "tags" },
      { key: "Deadline / notes", value: a.deadline || "—", kind: "text" },
    ];
  }
  if (questionnaireType === "music-video") {
    return [
      { key: "Client", value: a.clientName || "—", kind: "text" },
      { key: "Email", value: a.email || "—", kind: "text" },
      { key: "Artist / project", value: a.brandName || "—", kind: "text" },
      { key: "Artist or project link", value: a.website || "—", kind: "text" },
      { key: "Song title", value: a.songTitle || "—", kind: "text" },
      { key: "Music video type", value: a.videoType || "—", kind: "text" },
      { key: "Song link", value: a.songLink || "—", kind: "text" },
      { key: "Lyrics / script", value: { links: [], files: cleanList(a.scriptFiles), notes: a.lyricsText }, kind: "refs" },
      { key: "Song feeling", value: a.songMood || "—", kind: "text" },
      { key: "Target audience", value: a.targetAudience || "—", kind: "text" },
      { key: "Creative direction", value: a.visualConcept || "—", kind: "text" },
      { key: "Lyrics on screen", value: a.lyricTreatment || "—", kind: "text" },
      { key: "Visual style", value: cleanList(a.visualStyle), kind: "tags-coral" },
      { key: "Elements to include", value: a.includeElements || "—", kind: "text" },
      { key: "Elements to avoid", value: a.avoidElements || "—", kind: "text" },
      { key: "References", value: { links: cleanList(a.refLinks), files: [], notes: a.refNotes }, kind: "refs" },
      { key: "Assets", value: { links: [], files: cleanList(a.assetFiles), notes: "" }, kind: "refs" },
      { key: "Colors", value: { like: a.colorsLike, avoid: a.colorsAvoid }, kind: "colors" },
      { key: "Usage / platforms", value: cleanList(a.usage), kind: "tags" },
      { key: "Versions / formats", value: cleanList(a.formats), kind: "tags" },
      { key: "Duration / timing", value: a.durationNotes || "—", kind: "text" },
      { key: "Deadline / notes", value: a.deadline || "—", kind: "text" },
    ];
  }
  const styleNames = cleanList(a.styles).map(id => (LOGO_STYLES.find(s => s.id === id) || {}).name).filter(Boolean);
  const dash = "—";
  return [
    { key: "Brand name", value: a.brandName || dash, kind: "text" },
    { key: "Slogan", value: a.slogan || dash, kind: "text" },
    { key: "Business description", value: a.description || dash, kind: "text" },
    { key: "Target audience", value: a.audience || dash, kind: "text" },
    { key: "Preferred logo style", value: styleNames, kind: "tags" },
    { key: "Brand feeling", value: a.feelings, kind: "tags-coral" },
    { key: "References", value: { links: a.refLinks.filter(Boolean), files: a.refFiles, notes: a.refNotes }, kind: "refs" },
    { key: "Visual concept", value: (CONCEPT_OPTIONS.find(c => c.id === a.concept) || {}).title || dash, kind: "text" },
    { key: "Elements to include", value: a.conceptDetail || dash, kind: "text" },
    { key: "Elements to avoid", value: a.avoidElements || dash, kind: "text" },
    { key: "Colors", value: { like: a.colorsLike, avoid: a.colorsAvoid }, kind: "colors" },
    { key: "Typography", value: a.typography, kind: "tags" },
    { key: "Main usage", value: a.usage.filter(u => !u.includes("version")), kind: "tags" },
    { key: "Required versions & sizes", value: { versions: a.usage.filter(u => u.includes("version")), sizes: a.sizes }, kind: "versions" },
  ];
}

/* ---- Plain-text brief for copy ---- */
function briefToText(a, questionnaireType = a?.questionnaireType || "logo-design") {
  const secs = buildBriefSections(a, questionnaireType);
  const meta = getQuestionnaireMeta(questionnaireType);
  const lines = [meta.briefLabel, `Arigato Studio`, ``];
  const render = (s) => {
    switch (s.kind) {
      case "tags": case "tags-coral": return (s.value && s.value.length) ? s.value.join(", ") : "—";
      case "refs": {
        const parts = [];
        const links = s.value.links || [];
        const files = s.value.files || [];
        if (links.length) parts.push("Links: " + links.join("  |  "));
        if (files.length) parts.push("Files: " + files.map(f => f.name).join(", "));
        if (s.value.notes) parts.push("Notes: " + s.value.notes);
        return parts.length ? parts.join("\n  ") : "—";
      }
      case "colors": {
        const parts = [];
        if (s.value.like) parts.push("Preferred: " + s.value.like);
        if (s.value.avoid) parts.push("Avoid: " + s.value.avoid);
        return parts.length ? parts.join("\n  ") : "—";
      }
      case "versions": {
        const parts = [];
        if (s.value.versions.length) parts.push(s.value.versions.join(", "));
        if (s.value.sizes) parts.push("Sizes: " + s.value.sizes);
        return parts.length ? parts.join("\n  ") : "—";
      }
      default: return s.value || "—";
    }
  };
  secs.forEach(s => { lines.push(s.key.toUpperCase()); lines.push("  " + render(s)); lines.push(""); });
  return lines.join("\n");
}

/* ---- API helpers ---- */
async function apiJson(url, options = {}) {
  const res = await fetch(url, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(options.headers || {}),
    },
  });
  let data = null;
  try { data = await res.json(); } catch {}
  if (!res.ok) throw new Error(data?.error || data?.message || "Request failed");
  return data;
}
async function submitQuestionnaire(answers) {
  const questionnaireType = answers?.questionnaireType || "logo-design";
  const withOrder = ARIGATO_ORDER && !answers?.orderNumber ? { ...answers, orderNumber: ARIGATO_ORDER } : answers;
  return apiJson("/api/submissions", {
    method: "POST",
    body: JSON.stringify({ questionnaireType, answers: withOrder }),
  });
}
async function fetchSubmissions(adminKey) {
  return apiJson("/api/submissions", {
    headers: { "x-admin-key": adminKey || "" },
  });
}
async function updateSubmissionRemote(id, patch, adminKey) {
  return apiJson(`/api/submissions/${encodeURIComponent(id)}`, {
    method: "PATCH",
    headers: { "x-admin-key": adminKey || "" },
    body: JSON.stringify(patch),
  });
}

/* ---- localStorage fallback helpers from the prototype ---- */
const STORE_KEY = "arigato_logo_submissions_v1";
function loadSubmissions() {
  try { return JSON.parse(localStorage.getItem(STORE_KEY) || "[]"); } catch { return []; }
}
function saveSubmission(sub) {
  const all = loadSubmissions();
  all.unshift(sub);
  try { localStorage.setItem(STORE_KEY, JSON.stringify(all)); } catch {}
  return sub;
}
function updateSubmission(id, patch) {
  const all = loadSubmissions();
  const i = all.findIndex(s => s.id === id);
  if (i >= 0) { all[i] = { ...all[i], ...patch }; try { localStorage.setItem(STORE_KEY, JSON.stringify(all)); } catch {} }
  return all;
}

/* ---- color string → swatches (best-effort) ---- */
const NAMED = { red:"#E13F5B",blue:"#2A6FDB",navy:"#202739","dark blue":"#202739",green:"#2F7D5B",black:"#202739",white:"#FFFFFF",gold:"#C9A227",yellow:"#E5B53A",orange:"#E07A3A",purple:"#7A5AE0",pink:"#EB7689",teal:"#1F9E96",gray:"#97A0B8",grey:"#97A0B8",silver:"#C2C8D6",beige:"#E8E2D4",cream:"#F4EFE3",cyan:"#82FFFA",coral:"#E13F5B" };
function extractSwatches(str) {
  if (!str) return [];
  const out = [];
  const hexes = str.match(/#[0-9a-fA-F]{3,6}/g) || [];
  hexes.forEach(h => out.push(h));
  const low = str.toLowerCase();
  Object.keys(NAMED).forEach(n => { if (low.includes(n)) out.push(NAMED[n]); });
  return [...new Set(out)].slice(0, 6);
}

Object.assign(window, {
  Icon, Logo, StyleGlyph,
  LOGO_STYLES, FEELINGS, CONCEPT_OPTIONS, TYPO_STYLES, USAGE_OPTIONS,
  QUESTIONNAIRE_TYPES, getQuestionnaireMeta,
  LOGO_ANIMATION_TYPES, ANIMATION_FEELINGS, ANIMATION_USAGE, ANIMATION_FORMATS, ANIMATION_DURATIONS, AUDIO_OPTIONS,
  emptyAnswers, emptyLogoAnimationAnswers, buildBriefSections, briefToText,
  submitQuestionnaire, fetchSubmissions, updateSubmissionRemote,
  loadSubmissions, saveSubmission, updateSubmission, extractSwatches,
});
