// MomentIQ Creator Portal — shared primitives (icons, fields, stepper)
const { useState, useEffect, useRef } = React;

/* ---------- Inline icons (lucide-style, 1.8 stroke) ---------- */
function MqIcon({ d, size = 18, strokeWidth = 1.8, style, children }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" style={style} aria-hidden="true">
      {children || <path d={d}></path>}
    </svg>
  );
}
const IconLink = (p) => (
  <MqIcon {...p}>
    <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
    <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
  </MqIcon>
);
const IconWallet = (p) => (
  <MqIcon {...p}>
    <path d="M19 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2H5"></path>
    <circle cx="16.5" cy="13.5" r="1.2" fill="currentColor" stroke="none"></circle>
  </MqIcon>
);
const IconCheck = (p) => <MqIcon {...p} d="M20 6 9 17l-5-5" />;
const IconPlus = (p) => <MqIcon {...p}><path d="M12 5v14"></path><path d="M5 12h14"></path></MqIcon>;
const IconX = (p) => <MqIcon {...p}><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></MqIcon>;
const IconArrowRight = (p) => <MqIcon {...p}><path d="M5 12h14"></path><path d="m12 5 7 7-7 7"></path></MqIcon>;
const IconChevronLeft = (p) => <MqIcon {...p} d="m15 18-6-6 6-6" />;
const IconLock = (p) => (
  <MqIcon {...p}>
    <rect x="4" y="11" width="16" height="9" rx="2"></rect>
    <path d="M8 11V7a4 4 0 0 1 8 0v4"></path>
  </MqIcon>
);
const IconUpload = (p) => (
  <MqIcon {...p}>
    <path d="M21 15v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3"></path>
    <path d="m7 9 5-5 5 5"></path>
    <path d="M12 4v12"></path>
  </MqIcon>
);
const IconFileText = (p) => (
  <MqIcon {...p}>
    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
    <path d="M14 2v6h6"></path>
    <path d="M9 13h6"></path>
    <path d="M9 17h6"></path>
  </MqIcon>
);
const IconBank = (p) => (
  <MqIcon {...p}>
    <path d="m3 9 9-6 9 6"></path>
    <path d="M4 9v11"></path><path d="M20 9v11"></path>
    <path d="M8 13v4"></path><path d="M12 13v4"></path><path d="M16 13v4"></path>
    <path d="M3 20h18"></path>
  </MqIcon>
);
const IconPaypal = (p) => (
  <MqIcon {...p}>
    <path d="M7 21 9 3h6a4.5 4.5 0 0 1 4.4 5.5A5.5 5.5 0 0 1 14 13h-3.2L9.8 21z"></path>
  </MqIcon>
);
const IconSparkle = (p) => <MqIcon {...p} d="M12 3l1.9 5.6L19.5 10l-5.6 1.9L12 17.5l-1.9-5.6L4.5 10l5.6-1.4z" />;

/* ---------- Form primitives ---------- */
function Field({ label, hint, error, row, children }) {
  return (
    <label className={"cp-field" + (row ? " cp-field-row" : "")}>
      <span className="cp-field-label">{label}</span>
      {children}
      {error ? <span className="cp-field-error" role="alert">{error}</span> :
        hint ? <span className="cp-field-hint">{hint}</span> : null}
    </label>
  );
}

function TextInput({ value, onChange, placeholder, type = "text", invalid, mono, onKeyDown, autoFocus, inputMode }) {
  return (
    <input
      className={"cp-input" + (invalid ? " cp-input-invalid" : "") + (mono ? " cp-mono" : "")}
      type={type} value={value} placeholder={placeholder} autoFocus={autoFocus}
      inputMode={inputMode} spellCheck="false"
      onKeyDown={onKeyDown}
      onChange={(e) => onChange(e.target.value)} />
  );
}

function SelectInput({ value, onChange, options, placeholder }) {
  return (
    <div className="cp-select-wrap">
      <select className={"cp-input cp-select" + (value ? "" : " cp-select-empty")}
        value={value} onChange={(e) => onChange(e.target.value)}>
        <option value="" disabled>{placeholder}</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <MqIcon size={16} style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", opacity: 0.5 }} d="m6 9 6 6 6-6" />
    </div>
  );
}

/* ---------- Stepper ---------- */
function Stepper({ steps, current }) {
  return (
    <div className="cp-stepper" role="list">
      {steps.map((s, i) => {
        const state = i < current ? "done" : i === current ? "active" : "todo";
        return (
          <React.Fragment key={s}>
            {i > 0 && <span className={"cp-step-line" + (i <= current ? " is-filled" : "")}></span>}
            <span className={"cp-step is-" + state} role="listitem" aria-current={state === "active" ? "step" : undefined}>
              <span className="cp-step-dot">{state === "done" ? <IconCheck size={11} strokeWidth={2.6} /> : i + 1}</span>
              <span className="cp-step-name">{s}</span>
            </span>
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ---------- Success splash ---------- */
function SuccessSplash({ title, children, onReset, resetLabel }) {
  const [popped, setPopped] = useState(false);
  useEffect(() => {
    // Double rAF: only start the pop animation when the rendering timeline is
    // actually ticking; in a frozen iframe rAF never fires → base (visible) shows.
    let id2;
    const id1 = requestAnimationFrame(() => {
      id2 = requestAnimationFrame(() => setPopped(true));
    });
    return () => { cancelAnimationFrame(id1); if (id2) cancelAnimationFrame(id2); };
  }, []);
  return (
    <div className={"cp-success" + (popped ? " is-in" : "")}>
      <div className="cp-success-ring"><IconCheck size={30} strokeWidth={2.4} /></div>
      <h3 className="cp-success-title">{title}</h3>
      <div className="cp-success-body">{children}</div>
      {onReset && (
        <button type="button" className="cp-btn-ghost cp-btn-sm" onClick={onReset}>{resetLabel}</button>
      )}
    </div>
  );
}

/* ---------- Selectable method card ---------- */
function MethodCard({ icon, title, desc, selected, onClick, badge }) {
  return (
    <button type="button" className={"cp-method" + (selected ? " is-selected" : "")} onClick={onClick}>
      <span className="cp-method-icon">{icon}</span>
      <span className="cp-method-text">
        <span className="cp-method-title">{title}{badge && <span className="cp-method-badge">{badge}</span>}</span>
        <span className="cp-method-desc">{desc}</span>
      </span>
      <span className="cp-method-radio">{selected && <IconCheck size={12} strokeWidth={3} />}</span>
    </button>
  );
}

/* ---------- Embedded W-9 fill & sign (Dropbox Sign shape — packages/api-clients/src/dropbox-sign) ---------- */
function W9SignEmbed({ defaultName, signed, onSigned }) {
  const [legal, setLegal] = useState(defaultName || "");
  const [cls, setCls] = useState("Individual / sole proprietor");
  const [tin, setTin] = useState("");
  const [addr, setAddr] = useState("");
  const [sig, setSig] = useState("");
  const [errs, setErrs] = useState({});
  const sign = () => {
    const e = {};
    if (!legal.trim()) e.legal = "Required.";
    if (!/^\d{9}$/.test(tin.replace(/[^\d]/g, ""))) e.tin = "9 digits — SSN or EIN.";
    if (!addr.trim()) e.addr = "Required.";
    if (!sig.trim() || sig.trim().toLowerCase() !== legal.trim().toLowerCase()) e.sig = "Type your legal name exactly to sign.";
    setErrs(e);
    if (Object.keys(e).length) return;
    onSigned({ legal, cls });
  };
  if (signed) {
    return (
      <div className="cp-sign cp-sign-complete" role="status">
        <IconCheck size={18} strokeWidth={2.4} />
        <span><strong>W-9 signed &amp; filed.</strong> A copy is on its way to your email.</span>
      </div>
    );
  }
  return (
    <div className="cp-sign" aria-label="Embedded W-9 signing">
      <div className="cp-sign-head">
        <span className="cp-sign-brand"><IconFileText size={14} /> IRS Form W-9</span>
        <span className="cp-sign-power"><IconLock size={11} /> Securely embedded · Dropbox Sign</span>
      </div>
      <div className="cp-sign-grid">
        <Field label="Legal name" error={errs.legal}>
          <TextInput value={legal} onChange={setLegal} placeholder="As shown on your tax return" invalid={!!errs.legal} />
        </Field>
        <Field label="Federal tax classification">
          <SelectInput value={cls} onChange={setCls}
            options={["Individual / sole proprietor", "Single-member LLC", "C corporation", "S corporation", "Partnership"]}
            placeholder="Classification" />
        </Field>
        <Field label="SSN or EIN" error={errs.tin}>
          <TextInput value={tin} onChange={(v) => setTin(v.replace(/[^\d-]/g, ""))} mono inputMode="numeric"
            placeholder="XXX-XX-XXXX" invalid={!!errs.tin} />
        </Field>
        <Field label="Address" error={errs.addr}>
          <TextInput value={addr} onChange={setAddr} placeholder="Street, city, state, ZIP" invalid={!!errs.addr} />
        </Field>
      </div>
      <Field label="Signature" error={errs.sig} hint="Typing your legal name signs the form electronically.">
        <TextInput value={sig} onChange={setSig} placeholder="Type your full legal name" invalid={!!errs.sig} />
      </Field>
      <div className="cp-sign-foot">
        <span className="cp-sign-cert">By signing, you certify the information above is correct (IRS W-9, Rev. 3-2024).</span>
        <button type="button" className="mq-btn-primary cp-btn-ghost" onClick={sign}>Sign &amp; submit</button>
      </div>
    </div>
  );
}

Object.assign(window, {
  MqIcon, IconLink, IconWallet, IconCheck, IconPlus, IconX, IconArrowRight, IconChevronLeft,
  IconLock, IconUpload, IconFileText, IconBank, IconPaypal, IconSparkle,
  Field, TextInput, SelectInput, Stepper, SuccessSplash, MethodCard, W9SignEmbed,
});
