/* ============================================================
   Client Logo Questionnaire — interactive multi-step form
   ============================================================ */
var { useState, useEffect, useRef, useMemo } = React;

const STEPS = [
  { id: "basics", label: "Brand basics", eyebrow: "Step 01 / 05" },
  { id: "style", label: "Style direction", eyebrow: "Step 02 / 05" },
  { id: "concept", label: "Visual concept", eyebrow: "Step 03 / 05" },
  { id: "color", label: "Colors & type", eyebrow: "Step 04 / 05" },
  { id: "usage", label: "Usage & delivery", eyebrow: "Step 05 / 05" },
];

/* ---------- small field primitives ---------- */
function Label({ children, required, optional }) {
  return (
    <div className="field-label">
      {children}
      {required && <span className="req" title="Required">*</span>}
      {optional && <span className="optional">optional</span>}
    </div>
  );
}
function FieldError({ show, msg }) {
  if (!show) return null;
  return <div className="field-error"><Icon name="alert" size={14} /> {msg}</div>;
}

/* ---------- selectable controls ---------- */
function ChoiceCard({ selected, radio, onClick, title, desc }) {
  return (
    <button type="button" className={`choice ${radio ? "radio" : ""} ${selected ? "is-selected" : ""}`} onClick={onClick}>
      <span className="tick"><Icon name="check" size={13} stroke={2.4} /></span>
      <span className="choice-body">
        <span>{title}</span>
        {desc && <span className="desc">{desc}</span>}
      </span>
    </button>
  );
}
function Chip({ selected, onClick, children }) {
  return (
    <button type="button" className={`chip ${selected ? "is-selected" : ""}`} onClick={onClick}>
      {children}
      {selected && <span className="x"><Icon name="check" size={12} stroke={2.6} /></span>}
    </button>
  );
}

/* ---------- file upload ---------- */
function fmtSize(b) {
  if (b < 1024) return b + " B";
  if (b < 1024 * 1024) return (b / 1024).toFixed(0) + " KB";
  return (b / 1024 / 1024).toFixed(1) + " MB";
}
function makeThumb(file) {
  return new Promise((resolve) => {
    if (!file.type.startsWith("image/")) { resolve(null); return; }
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      const max = 160, scale = Math.min(1, max / Math.max(img.width, img.height));
      const c = document.createElement("canvas");
      c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale);
      c.getContext("2d").drawImage(img, 0, 0, c.width, c.height);
      URL.revokeObjectURL(url);
      try { resolve(c.toDataURL("image/jpeg", 0.7)); } catch { resolve(null); }
    };
    img.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
    img.src = url;
  });
}
function fileToDataUrl(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}
function Uploader({ files, onChange, title = "Drag images here or click to upload", hint = "PNG, JPG, SVG, PDF, AI or EPS · up to 5 files", accept = "image/*,.pdf,.svg,.ai,.eps" }) {
  const [drag, setDrag] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef(null);
  const add = async (list) => {
    setError("");
    const maxFileBytes = 2.5 * 1024 * 1024;
    const maxTotalBytes = 3.5 * 1024 * 1024;
    const existingBytes = files.reduce((sum, f) => sum + (f.size || 0), 0);
    const arr = Array.from(list).slice(0, 5 - files.length);
    const mapped = [];
    let runningBytes = existingBytes;
    for (const f of arr) {
      if (f.size > maxFileBytes) {
        setError("One file is too large. Please upload files under 2.5 MB or paste a reference link.");
        continue;
      }
      if (runningBytes + f.size > maxTotalBytes) {
        setError("The total upload is too large. Please keep files light or paste reference links.");
        continue;
      }
      const thumb = await makeThumb(f);
      const dataUrl = await fileToDataUrl(f);
      mapped.push({ name: f.name, size: f.size, type: f.type, thumb, dataUrl });
      runningBytes += f.size;
    }
    onChange([...files, ...mapped]);
  };
  return (
    <div>
      <div
        className={`dropzone ${drag ? "is-drag" : ""}`}
        onClick={() => inputRef.current && inputRef.current.click()}
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); add(e.dataTransfer.files); }}
      >
        <div className="dz-icon"><Icon name="upload" size={22} /></div>
        <div className="dz-title">{title}</div>
        <div className="dz-sub">{hint}</div>
        <input ref={inputRef} type="file" accept={accept} multiple style={{ display: "none" }}
          onChange={(e) => { add(e.target.files); e.target.value = ""; }} />
      </div>
      {error && <div className="field-error"><Icon name="alert" size={14} /> {error}</div>}
      {files.length > 0 && (
        <div className="file-list">
          {files.map((f, i) => (
            <div className="file-row" key={i}>
              <span className="file-thumb">{f.thumb ? <img src={f.thumb} alt="" /> : <Icon name="file" size={16} />}</span>
              <span className="file-meta">
                <div className="file-name">{f.name}</div>
                <div className="file-size">{fmtSize(f.size)}</div>
              </span>
              <button className="file-x" onClick={() => onChange(files.filter((_, j) => j !== i))} aria-label="Remove"><Icon name="x" size={15} /></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- the steps ---------- */
function StepBasics({ a, set, errors, T }) {
  return (
    <div className="card step-anim">
      <div className="step-head">
        <div className="step-eyebrow">{STEPS[0].eyebrow}</div>
        <h2 className="step-title">{T.editorial ? <>Let's start with the <em>basics</em></> : "Let's start with the basics"}</h2>
        <p className="step-sub">The essentials that anchor every logo brief.</p>
      </div>
      <div className="field">
        <Label required>What is the exact name you want in the logo?</Label>
        <p className="field-help">Type it exactly as it should appear — capitalization, spacing and any “&amp;” included.</p>
        <input className={`input ${errors.brandName ? "has-error" : ""}`} value={a.brandName}
          onChange={(e) => set({ brandName: e.target.value })} placeholder="e.g. Northbound Coffee Co." />
        <FieldError show={errors.brandName} msg="Please enter the name for the logo." />
      </div>
      <div className="field">
        <Label optional>Do you want to include a slogan or tagline?</Label>
        <input className="input" value={a.slogan} onChange={(e) => set({ slogan: e.target.value })} placeholder="e.g. Roasted small, served warm" />
      </div>
      <div className="field">
        <Label required>What does your business or brand do?</Label>
        <p className="field-help">A sentence or two in plain language — what you offer and to whom.</p>
        <textarea className={`textarea ${errors.description ? "has-error" : ""}`} value={a.description}
          onChange={(e) => set({ description: e.target.value })} rows={3} placeholder="We roast and ship specialty coffee to small cafés…" />
        <FieldError show={errors.description} msg="A short description helps us design the right mark." />
      </div>
      <div className="field">
        <Label>Who is your target audience?</Label>
        <input className="input" value={a.audience} onChange={(e) => set({ audience: e.target.value })} placeholder="e.g. Independent café owners, 25–45" />
      </div>
    </div>
  );
}

function StepStyle({ a, set, T }) {
  const toggleStyle = (id) => {
    if (id === "unsure") { set({ styles: a.styles.includes("unsure") ? [] : ["unsure"] }); return; }
    const next = a.styles.filter(s => s !== "unsure");
    set({ styles: next.includes(id) ? next.filter(s => s !== id) : [...next, id] });
  };
  const toggleFeel = (f) => set({ feelings: a.feelings.includes(f) ? a.feelings.filter(x => x !== f) : [...a.feelings, f] });
  const setLink = (i, v) => { const l = [...a.refLinks]; l[i] = v; set({ refLinks: l }); };
  return (
    <div className="card step-anim">
      <div className="step-head">
        <div className="step-eyebrow">{STEPS[1].eyebrow}</div>
        <h2 className="step-title">{T.editorial ? <>The <em>look</em> & feel</> : "The look & feel"}</h2>
        <p className="step-sub">Point us in a direction — you can pick more than one.</p>
      </div>

      <div className="field">
        <Label>What logo style do you prefer?</Label>
        <p className="field-help">Select all that appeal. Not sure? That's a valid answer too.</p>
        {T.stylePicker === "cards" ? (
          <div className="stylecard-grid">
            {LOGO_STYLES.map(s => (
              <button type="button" key={s.id} className={`stylecard ${a.styles.includes(s.id) ? "is-selected" : ""}`} onClick={() => toggleStyle(s.id)}>
                <span className="corner-tick"><Icon name="check" size={12} stroke={2.6} /></span>
                <span className="glyph"><StyleGlyph kind={s.glyph} /></span>
                <span className="name">{s.name}</span>
              </button>
            ))}
          </div>
        ) : (
          <div className="choice-grid cols-2">
            {LOGO_STYLES.map(s => (
              <ChoiceCard key={s.id} selected={a.styles.includes(s.id)} onClick={() => toggleStyle(s.id)} title={s.name} />
            ))}
          </div>
        )}
      </div>

      <div className="field">
        <Label>What feeling should the logo communicate?</Label>
        <p className="field-help">Choose the words that fit best.</p>
        {T.tagInput === "chips" ? (
          <div className="chip-wrap">
            {FEELINGS.map(f => <Chip key={f} selected={a.feelings.includes(f)} onClick={() => toggleFeel(f)}>{f}</Chip>)}
          </div>
        ) : (
          <div className="choice-grid cols-3">
            {FEELINGS.map(f => <ChoiceCard key={f} selected={a.feelings.includes(f)} onClick={() => toggleFeel(f)} title={f} />)}
          </div>
        )}
      </div>

      <div className="field">
        <Label>Share 2–5 logo references you like</Label>
        <p className="field-help">Upload images, paste links, and tell us what draws you to them.</p>
        <Uploader files={a.refFiles} onChange={(refFiles) => set({ refFiles })} />
        <div className="link-rows" style={{ marginTop: 12 }}>
          {a.refLinks.map((l, i) => (
            <div className="link-row" key={i}>
              <span style={{ color: "var(--navy-400)", flex: "none", display: "grid", placeItems: "center" }}><Icon name="link" size={16} /></span>
              <input className="input" value={l} onChange={(e) => setLink(i, e.target.value)} placeholder="https://…" />
              {a.refLinks.length > 1 && (
                <button className="file-x" onClick={() => set({ refLinks: a.refLinks.filter((_, j) => j !== i) })} aria-label="Remove link"><Icon name="x" size={15} /></button>
              )}
            </div>
          ))}
          {a.refLinks.length < 5 && (
            <button className="btn btn-ghost btn-sm add-link" onClick={() => set({ refLinks: [...a.refLinks, ""] })}><Icon name="plus" size={14} /> Add another link</button>
          )}
        </div>
        <textarea className="textarea" style={{ marginTop: 12 }} value={a.refNotes} onChange={(e) => set({ refNotes: e.target.value })} rows={2}
          placeholder="What do you like about these references? (e.g. the simple mark, the color, the typography)" />
      </div>
    </div>
  );
}

function StepConcept({ a, set, T }) {
  return (
    <div className="card step-anim">
      <div className="step-head">
        <div className="step-eyebrow">{STEPS[2].eyebrow}</div>
        <h2 className="step-title">{T.editorial ? <>What goes <em>inside</em> the mark</> : "What goes inside the mark"}</h2>
        <p className="step-sub">However formed or loose your idea is, tell us where you stand.</p>
      </div>
      <div className="field">
        <Label>Do you already have a specific idea, symbol or concept?</Label>
        <div className="choice-grid" style={{ marginTop: 4 }}>
          {CONCEPT_OPTIONS.map(c => (
            <ChoiceCard key={c.id} radio selected={a.concept === c.id} onClick={() => set({ concept: c.id })} title={c.title} desc={c.desc} />
          ))}
        </div>
      </div>
      <div className="field">
        <Label>Describe what you want included in the logo</Label>
        <p className="field-help">Mention icons, letters, symbols, people, animals, objects, shapes — anything important for the design.</p>
        <textarea className="textarea" value={a.conceptDetail} onChange={(e) => set({ conceptDetail: e.target.value })} rows={4}
          placeholder="e.g. a mountain peak combined with a coffee bean, lowercase wordmark…" />
      </div>
      <div className="field">
        <Label>Is there anything you do not want in the logo?</Label>
        <textarea className="textarea" value={a.avoidElements} onChange={(e) => set({ avoidElements: e.target.value })} rows={2}
          placeholder="e.g. no gradients, no cartoon style, avoid the color green" />
      </div>
    </div>
  );
}

function StepColor({ a, set, T }) {
  const toggleTypo = (t) => {
    if (t === "Not sure") { set({ typography: a.typography.includes("Not sure") ? [] : ["Not sure"] }); return; }
    const next = a.typography.filter(x => x !== "Not sure");
    set({ typography: next.includes(t) ? next.filter(x => x !== t) : [...next, t] });
  };
  return (
    <div className="card step-anim">
      <div className="step-head">
        <div className="step-eyebrow">{STEPS[3].eyebrow}</div>
        <h2 className="step-title">{T.editorial ? <>Color & <em>type</em></> : "Color & type"}</h2>
        <p className="step-sub">Set the palette and lettering mood. Approximate is fine.</p>
      </div>
      <div className="row-2">
        <div className="field" style={{ marginBottom: 0 }}>
          <Label>Preferred colors</Label>
          <input className="input" value={a.colorsLike} onChange={(e) => set({ colorsLike: e.target.value })} placeholder="e.g. deep navy, warm coral, off-white" />
        </div>
        <div className="field" style={{ marginBottom: 0 }}>
          <Label>Colors to avoid</Label>
          <input className="input" value={a.colorsAvoid} onChange={(e) => set({ colorsAvoid: e.target.value })} placeholder="e.g. bright green, neon" />
        </div>
      </div>
      <div className="field" style={{ marginTop: "var(--space-6)" }}>
        <Label>Typography style</Label>
        <p className="field-help">Pick the lettering character you're drawn to.</p>
        {T.tagInput === "chips" ? (
          <div className="chip-wrap">{TYPO_STYLES.map(t => <Chip key={t} selected={a.typography.includes(t)} onClick={() => toggleTypo(t)}>{t}</Chip>)}</div>
        ) : (
          <div className="choice-grid cols-3">{TYPO_STYLES.map(t => <ChoiceCard key={t} selected={a.typography.includes(t)} onClick={() => toggleTypo(t)} title={t} />)}</div>
        )}
      </div>
    </div>
  );
}

function StepUsage({ a, set, T }) {
  const usageMain = USAGE_OPTIONS.filter(u => !u.includes("version"));
  const usageVer = USAGE_OPTIONS.filter(u => u.includes("version"));
  const toggle = (u) => set({ usage: a.usage.includes(u) ? a.usage.filter(x => x !== u) : [...a.usage, u] });
  return (
    <div className="card step-anim">
      <div className="step-head">
        <div className="step-eyebrow">{STEPS[4].eyebrow}</div>
        <h2 className="step-title">{T.editorial ? <>Where it will <em>live</em></> : "Where it will live"}</h2>
        <p className="step-sub">So we deliver the right files, versions and sizes.</p>
      </div>
      <div className="field">
        <Label>Where will you use the logo?</Label>
        <div className="choice-grid cols-2">
          {usageMain.map(u => <ChoiceCard key={u} selected={a.usage.includes(u)} onClick={() => toggle(u)} title={u} />)}
        </div>
      </div>
      <div className="field">
        <Label>Which versions do you need?</Label>
        <div className="chip-wrap">
          {usageVer.map(u => <Chip key={u} selected={a.usage.includes(u)} onClick={() => toggle(u)}>{u}</Chip>)}
        </div>
      </div>
      <div className="field">
        <Label optional>Any specific sizes you need?</Label>
        <textarea className="textarea" value={a.sizes} onChange={(e) => set({ sizes: e.target.value })} rows={2}
          placeholder="e.g. 1024×1024 app icon, 2400px wide banner, favicon" />
      </div>
    </div>
  );
}

window.QStepComponents = { StepBasics, StepStyle, StepConcept, StepColor, StepUsage };
window.QShared = { Label, FieldError, ChoiceCard, Chip, Uploader, STEPS };
