// ThaiHao wizard steps: Step1-6, Review, Success.
// Each step is a functional component receiving (data, update, errors, t, lang).

const { useState: useS, useMemo, useEffect: useE } = React;

// ---------- helper: field with controlled value + onChange wired to update(key) ----------
const useField = (data, update, errors, name, onFieldBlur) => ({
  value: data[name],
  onChange: (v) => update(name, v),
  onBlur: onFieldBlur ? () => onFieldBlur(name) : undefined,
  error: errors[name],
});

// ============================================================
// STEP 1 — Company
// ============================================================
function Step1Company({ data, update, errors, t, onFieldBlur }) {
  const f = (n) => useField(data, update, errors, n, onFieldBlur);
  const provinceOptions = useMemo(
    () => t.provinces.map((p) => ({ value: p, label: p })),
    [t]
  );
  return (
    <div className="field-stack">
      {/* Identity */}
      <div className="section-head">
        <span>{t.s1_sec_identity}</span>
        <span className="line"></span>
      </div>

      <Field
        t={t} required
        label={t.s1_company_th}
        htmlFor="company_th"
        error={errors.company_th && t.err_required(t.s1_company_th)}
      >
        <TextInput
          id="company_th"
          placeholder={t.s1_company_th_ph}
          {...f("company_th")}
          onBlur={() => {}}
        />
      </Field>

      <div className="field-row">
        <Field
          t={t} optional label={t.s1_company_en} htmlFor="company_en"
        >
          <TextInput id="company_en" placeholder={t.s1_company_en_ph} {...f("company_en")} />
        </Field>
        <Field
          t={t} optional label={t.s1_company_cn} htmlFor="company_cn"
          help={t.s1_company_cn_help}
        >
          <TextInput id="company_cn" placeholder={t.s1_company_cn_ph} {...f("company_cn")} />
        </Field>
      </div>

      <Field
        t={t} required
        label={t.s1_tax} htmlFor="tax_id"
        help={!errors.tax_id ? t.s1_tax_help : undefined}
        error={errors.tax_id === "required" ? t.err_required(t.s1_tax) : errors.tax_id === "tax" ? t.err_tax : undefined}
      >
        <TextInput
          id="tax_id"
          mono
          placeholder={t.s1_tax_ph}
          value={Format.tax13(data.tax_id)}
          onChange={(v) => update("tax_id", v)}
          onBlur={() => onFieldBlur && onFieldBlur("tax_id")}
          inputMode="numeric"
        />
      </Field>

      <Field
        t={t} required
        label={t.s1_biz_type} htmlFor="biz_type"
        error={errors.biz_type && t.err_required(t.s1_biz_type)}
      >
        <Select
          id="biz_type"
          options={t.s1_biz_type_options}
          placeholder="—"
          {...f("biz_type")}
        />
      </Field>

      {/* Address */}
      <div className="section-head" style={{marginTop: 24}}>
        <span>{t.s1_sec_address}</span>
        <span className="line"></span>
      </div>

      <Field
        t={t} required
        label={t.s1_address} htmlFor="address"
        error={errors.address && t.err_required(t.s1_address)}
      >
        <TextInput id="address" placeholder={t.s1_address_ph} {...f("address")} />
      </Field>

      <div className="field-row">
        <Field
          t={t} required
          label={t.s1_province} htmlFor="province"
          error={errors.province && t.err_required(t.s1_province)}
        >
          <Combobox
            id="province"
            options={provinceOptions}
            placeholder={t.s1_province_ph}
            value={data.province}
            onChange={(v) => update("province", v)}
            onBlur={() => onFieldBlur && onFieldBlur("province")}
            error={errors.province}
          />
        </Field>
        <Field t={t} optional label={t.s1_postcode} htmlFor="postcode">
          <TextInput id="postcode" mono placeholder="10110" inputMode="numeric" {...f("postcode")} />
        </Field>
      </div>

      {/* Profile */}
      <div className="section-head" style={{marginTop: 24}}>
        <span>{t.s1_sec_profile}</span>
        <span className="line"></span>
      </div>

      <div className="field-row">
        <Field
          t={t} optional label={t.s1_year} htmlFor="year"
          error={errors.year === "year" ? t.err_year : undefined}
        >
          <TextInput id="year" mono placeholder={t.s1_year_ph} inputMode="numeric" {...f("year")} />
        </Field>
        <Field t={t} optional label={t.s1_employees} htmlFor="employees">
          <Select id="employees" options={t.s1_employees_options} placeholder="—" {...f("employees")} />
        </Field>
      </div>

      {/* Online */}
      <div className="section-head" style={{marginTop: 24}}>
        <span>{t.s1_sec_online}</span>
        <span className="line"></span>
      </div>

      <Field
        t={t} optional label={t.s1_website} htmlFor="website"
        error={errors.website === "url" ? t.err_url : undefined}
      >
        <TextInput id="website" placeholder="https://www.example.com" {...f("website")} />
      </Field>

      <div className="field-row">
        <Field t={t} optional label={t.s1_facebook} htmlFor="facebook">
          <TextInput id="facebook" placeholder={t.s1_facebook_ph} {...f("facebook")} />
        </Field>
        <Field t={t} optional label={t.s1_lineoa} htmlFor="lineoa">
          <TextInput id="lineoa" placeholder={t.s1_lineoa_ph} {...f("lineoa")} />
        </Field>
      </div>
    </div>
  );
}

// ============================================================
// STEP 2 — Contact
// ============================================================
function Step2Contact({ data, update, errors, t, onFieldBlur }) {
  const f = (n) => useField(data, update, errors, n, onFieldBlur);
  return (
    <div className="field-stack">
      <div className="field-row">
        <Field
          t={t} required label={t.s2_name} htmlFor="contact_name"
          error={errors.contact_name && t.err_required(t.s2_name)}
        >
          <TextInput id="contact_name" placeholder={t.s2_name_ph} {...f("contact_name")} />
        </Field>
        <Field
          t={t} required label={t.s2_position} htmlFor="contact_position"
          error={errors.contact_position && t.err_required(t.s2_position)}
        >
          <TextInput id="contact_position" placeholder={t.s2_position_ph} {...f("contact_position")} />
        </Field>
      </div>

      <Field
        t={t} required label={t.s2_phone} htmlFor="contact_phone"
        help={!errors.contact_phone ? t.s2_phone_help : undefined}
        error={
          errors.contact_phone === "required" ? t.err_required(t.s2_phone) :
          errors.contact_phone === "phone" ? t.err_phone : undefined
        }
      >
        <div className={`input-with-prefix ${errors.contact_phone ? "is-error" : ""}`}>
          <span className="input-prefix">+66</span>
          <input
            type="tel"
            id="contact_phone"
            className="field-input is-mono"
            placeholder="08-XXXX-XXXX"
            value={Format.phoneTH(data.contact_phone)}
            onChange={(e) => update("contact_phone", e.target.value)}
            onBlur={() => onFieldBlur && onFieldBlur("contact_phone")}
            inputMode="numeric"
          />
        </div>
      </Field>

      <Field
        t={t} required label={t.s2_email} htmlFor="contact_email"
        error={
          errors.contact_email === "required" ? t.err_required(t.s2_email) :
          errors.contact_email === "email" ? t.err_email : undefined
        }
      >
        <TextInput id="contact_email" placeholder={t.s2_email_ph} type="email" {...f("contact_email")} />
      </Field>

      <div className="field-row">
        <Field t={t} optional label={t.s2_line} htmlFor="contact_line">
          <TextInput id="contact_line" placeholder={t.s2_line_ph} {...f("contact_line")} />
        </Field>
        <Field
          t={t} recommended label={t.s2_wechat} htmlFor="contact_wechat"
          help={t.s2_wechat_help}
        >
          <TextInput id="contact_wechat" placeholder={t.s2_wechat_ph} {...f("contact_wechat")} />
        </Field>
      </div>
    </div>
  );
}

// ============================================================
// STEP 3 — Documents
// ============================================================
function Step3Documents({ data, update, errors, t }) {
  const setFiles = (key, files) => update(key, files);

  const single = (key) => {
    const cur = data[key] || [];
    return {
      onAdd: (added) => setFiles(key, added.slice(0, 1)),
      onRemove: (id) => setFiles(key, cur.filter((f) => f.id !== id)),
      files: cur,
    };
  };
  const multi = (key) => {
    const cur = data[key] || [];
    return {
      onAdd: (added) => setFiles(key, [...cur, ...added]),
      onRemove: (id) => setFiles(key, cur.filter((f) => f.id !== id)),
      files: cur,
    };
  };

  const cert = single("doc_cert");
  const logo = single("doc_logo");
  const id_doc = single("doc_id");
  const lic = multi("doc_licenses");

  const renderFiles = (files, onRemove) =>
    files.length > 0 ? (
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 12 }}>
        {files.map((f) => (
          <UploadedFile key={f.id} file={f} onRemove={() => onRemove(f.id)} />
        ))}
      </div>
    ) : null;

  return (
    <div className="field-stack">
      <Field
        t={t} required label={t.s3_cert} help={t.s3_cert_help}
        error={errors.doc_cert && t.err_required(t.s3_cert)}
      >
        {cert.files.length === 0 ? (
          <Uploader
            accept="application/pdf"
            onAdd={cert.onAdd}
            dropLabel={t.s3_drop}
            helpLabel="PDF"
            icon="file-type-pdf"
          />
        ) : renderFiles(cert.files, cert.onRemove)}
      </Field>

      <Field
        t={t} required label={t.s3_logo} help={t.s3_logo_help}
        error={errors.doc_logo && t.err_required(t.s3_logo)}
      >
        {logo.files.length === 0 ? (
          <Uploader
            accept="image/png,image/svg+xml"
            onAdd={logo.onAdd}
            dropLabel={t.s3_drop}
            helpLabel="PNG · SVG"
            icon="photo"
          />
        ) : renderFiles(logo.files, logo.onRemove)}
      </Field>

      <Field
        t={t} required icon="shield-check" label={t.s3_id} help={t.s3_id_help}
        error={errors.doc_id && t.err_required(t.s3_id)}
      >
        {id_doc.files.length === 0 ? (
          <Uploader
            accept="application/pdf,image/*"
            onAdd={id_doc.onAdd}
            dropLabel={t.s3_drop}
            helpLabel="PDF · JPG"
            icon="file-text"
          />
        ) : renderFiles(id_doc.files, id_doc.onRemove)}
      </Field>
      <TrustNote>{t.s3_id_trust}</TrustNote>

      <Field
        t={t} optional label={t.s3_licenses} help={t.s3_licenses_help}
      >
        <Uploader
          accept="application/pdf,image/*"
          multiple
          onAdd={lic.onAdd}
          dropLabel={t.s3_drop_multi}
          helpLabel="PDF · JPG"
          icon="certificate"
        />
        {renderFiles(lic.files, lic.onRemove)}
      </Field>
    </div>
  );
}

// ============================================================
// STEP 4 — Products (repeatable)
// ============================================================
function ProductCard({ idx, product, onChange, onRemove, errors, t, expanded, onToggle }) {
  const setField = (key, value) => onChange({ ...product, [key]: value });
  const e = errors || {};

  const heading = product.name_th || t.s4_product(idx + 1);

  return (
    <div className={`product-card ${expanded ? "is-active" : ""}`}>
      <div
        className={`product-head ${expanded ? "" : "is-collapsed"}`}
        onClick={onToggle}
        role="button"
        tabIndex={0}
        onKeyDown={(ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); onToggle(); } }}
        aria-expanded={expanded}
      >
        <div className="product-head-left">
          <span className="product-head-num">{idx + 1}</span>
          <div style={{minWidth: 0}}>
            <div className="product-head-title">{heading}</div>
            {product.category && <div className="body-sm" style={{marginTop: 2}}>{product.category}</div>}
          </div>
        </div>
        <div className="product-head-actions">
          {onRemove && (
            <IconButton icon="trash" label={t.s4_remove_product} onClick={(ev) => { ev.stopPropagation(); onRemove(); }} />
          )}
          <IconButton icon={expanded ? "chevron-up" : "chevron-down"} label={expanded ? t.close : t.edit} onClick={(ev) => { ev.stopPropagation(); onToggle(); }} />
        </div>
      </div>

      {expanded && (
        <div className="product-body">
          <div className="field-stack">
            <Field
              t={t} required label={t.s4_name_th} htmlFor={`p${idx}_name_th`}
              error={e.name_th && t.err_required(t.s4_name_th)}
            >
              <TextInput
                id={`p${idx}_name_th`}
                value={product.name_th || ""}
                onChange={(v) => setField("name_th", v)}
              />
            </Field>
            <div className="field-row">
              <Field t={t} optional label={t.s4_name_en} htmlFor={`p${idx}_name_en`}>
                <TextInput id={`p${idx}_name_en`} value={product.name_en || ""} onChange={(v) => setField("name_en", v)} />
              </Field>
              <Field t={t} optional label={t.s4_name_cn} htmlFor={`p${idx}_name_cn`}>
                <TextInput id={`p${idx}_name_cn`} value={product.name_cn || ""} onChange={(v) => setField("name_cn", v)} />
              </Field>
            </div>

            <Field
              t={t} required label={t.s4_category} htmlFor={`p${idx}_category`}
              error={e.category && t.err_required(t.s4_category)}
            >
              <Select
                id={`p${idx}_category`}
                options={t.s4_category_options}
                placeholder="—"
                value={product.category || ""}
                onChange={(v) => setField("category", v)}
              />
            </Field>

            <Field t={t} optional label={t.s4_desc} htmlFor={`p${idx}_desc`}>
              <Textarea
                id={`p${idx}_desc`}
                value={product.description || ""}
                onChange={(v) => setField("description", v)}
                placeholder={t.s4_desc_ph}
                maxLength={500}
                showCounter
                rows={4}
              />
            </Field>

            <div className="field-row">
              <Field t={t} optional label={`${t.s4_price_retail} (${t.s4_unit_thb})`} htmlFor={`p${idx}_price_retail`}>
                <TextInput
                  id={`p${idx}_price_retail`}
                  mono rightAlign inputMode="decimal"
                  placeholder="0.00"
                  value={Format.money(product.price_retail)}
                  onChange={(v) => setField("price_retail", Format.moneyRaw(v))}
                />
              </Field>
              <Field t={t} optional label={`${t.s4_price_wholesale} (${t.s4_unit_thb})`} htmlFor={`p${idx}_price_wholesale`}>
                <TextInput
                  id={`p${idx}_price_wholesale`}
                  mono rightAlign inputMode="decimal"
                  placeholder="0.00"
                  value={Format.money(product.price_wholesale)}
                  onChange={(v) => setField("price_wholesale", Format.moneyRaw(v))}
                />
              </Field>
            </div>

            <div className="field-row-3">
              <Field t={t} optional label={t.s4_size} htmlFor={`p${idx}_size`}>
                <TextInput id={`p${idx}_size`} value={product.size || ""} onChange={(v) => setField("size", v)} placeholder="100 ml" />
              </Field>
              <Field t={t} optional label={t.s4_weight} htmlFor={`p${idx}_weight`}>
                <TextInput id={`p${idx}_weight`} value={product.weight || ""} onChange={(v) => setField("weight", v)} placeholder="150 g" />
              </Field>
              <Field t={t} optional label={t.s4_packaging} htmlFor={`p${idx}_packaging`}>
                <TextInput id={`p${idx}_packaging`} value={product.packaging || ""} onChange={(v) => setField("packaging", v)} />
              </Field>
            </div>

            <Field t={t} optional label={t.s4_hs} help={t.s4_hs_help} htmlFor={`p${idx}_hs`}>
              <TextInput
                id={`p${idx}_hs`} mono inputMode="numeric"
                placeholder="3304.99"
                value={product.hs_code || ""}
                onChange={(v) => setField("hs_code", v)}
              />
            </Field>

            <Field t={t} optional label={t.s4_certs}>
              <ChoiceGrid
                multi options={t.s4_certs_options}
                value={product.certs || []}
                onChange={(v) => setField("certs", v)}
              />
            </Field>

            <div className="field-row">
              <Field t={t} optional label={`${t.s4_capacity} (${t.s4_unit_unit})`} htmlFor={`p${idx}_capacity`}>
                <TextInput
                  id={`p${idx}_capacity`} mono rightAlign inputMode="numeric"
                  value={Format.money(product.capacity)}
                  onChange={(v) => setField("capacity", Format.moneyRaw(v))}
                />
              </Field>
              <Field t={t} optional label={`${t.s4_moq} (${t.s4_unit_unit})`} htmlFor={`p${idx}_moq`}>
                <TextInput
                  id={`p${idx}_moq`} mono rightAlign inputMode="numeric"
                  value={Format.money(product.moq)}
                  onChange={(v) => setField("moq", Format.moneyRaw(v))}
                />
              </Field>
            </div>

            <Field t={t} optional label={t.s4_images} help={t.s4_images_help}>
              <ImageGrid
                images={product.images || []}
                onAdd={(imgs) => setField("images", [...(product.images || []), ...imgs].slice(0, 10))}
                onRemove={(id) => setField("images", (product.images || []).filter((i) => i.id !== id))}
                onReorder={(from, to) => {
                  const arr = [...(product.images || [])];
                  const [moved] = arr.splice(from, 1);
                  arr.splice(to, 0, moved);
                  setField("images", arr);
                }}
                max={10}
              />
            </Field>

            <Field t={t} optional label={t.s4_pkg_lang}>
              <ChoiceGrid
                multi options={t.s4_pkg_lang_options}
                value={product.pkg_lang || []}
                onChange={(v) => setField("pkg_lang", v)}
              />
            </Field>

            <Field t={t} optional label={t.s4_barcode}>
              <div style={{maxWidth: 280}}>
                <Seg
                  options={[
                    { value: "yes", label: t.s4_yes },
                    { value: "no", label: t.s4_no },
                  ]}
                  value={product.barcode || ""}
                  onChange={(v) => setField("barcode", v)}
                />
              </div>
            </Field>
          </div>
        </div>
      )}
    </div>
  );
}

function Step4Products({ data, update, errors, t }) {
  const products = data.products || [];
  const [expandedIdx, setExpandedIdx] = useS(products.length - 1);

  const setProducts = (next) => update("products", next);
  const addProduct = () => {
    if (products.length >= 5) return;
    const next = [...products, { id: Math.random().toString(36).slice(2), certs: [], images: [], pkg_lang: [] }];
    setProducts(next);
    setExpandedIdx(next.length - 1);
  };
  const removeProduct = (idx) => {
    const next = products.filter((_, i) => i !== idx);
    setProducts(next);
    setExpandedIdx(Math.min(expandedIdx, next.length - 1));
  };
  const changeProduct = (idx, next) => {
    const arr = products.slice();
    arr[idx] = next;
    setProducts(arr);
  };

  return (
    <div className="field-stack">
      {products.length === 0 && (
        <div style={{
          textAlign: "center", padding: "24px 16px",
          border: "1px dashed var(--outline-variant)",
          borderRadius: "var(--r-lg)",
          background: "var(--surface-container-low)",
        }}>
          <p className="body-md" style={{marginBottom: 12}}>
            {t.s4_intro}
          </p>
          <Button variant="primary" icon="plus" onClick={addProduct}>{t.s4_add}</Button>
        </div>
      )}

      {products.map((p, idx) => (
        <ProductCard
          key={p.id}
          idx={idx}
          product={p}
          errors={(errors.products && errors.products[idx]) || {}}
          onChange={(next) => changeProduct(idx, next)}
          onRemove={products.length > 1 ? () => removeProduct(idx) : null}
          t={t}
          expanded={expandedIdx === idx}
          onToggle={() => setExpandedIdx(expandedIdx === idx ? -1 : idx)}
        />
      ))}

      {products.length > 0 && products.length < 5 && (
        <div>
          <Button variant="tertiary" icon="plus" onClick={addProduct}>{t.s4_add}</Button>
        </div>
      )}
      {products.length >= 5 && (
        <div className="body-sm" style={{textAlign:"center"}}>{t.s4_max}</div>
      )}
    </div>
  );
}

// ============================================================
// STEP 5 — Cross-border readiness
// ============================================================
function Step5Readiness({ data, update, errors, t, onFieldBlur }) {
  const f = (n) => useField(data, update, errors, n, onFieldBlur);
  return (
    <div className="field-stack">
      <Field t={t} required label={t.s5_exported}
        error={errors.exported && t.err_required(t.s5_exported)}>
        <div style={{maxWidth: 340}}>
          <Seg
            options={[
              { value: "yes", label: t.s5_exported_yes },
              { value: "no", label: t.s5_exported_no },
            ]}
            value={data.exported || ""}
            onChange={(v) => update("exported", v)}
          />
        </div>
      </Field>

      {data.exported === "yes" && (
        <Field t={t} optional label={t.s5_exported_channel} htmlFor="exported_channel">
          <TextInput
            id="exported_channel"
            placeholder={t.s5_exported_channel_ph}
            {...f("exported_channel")}
          />
        </Field>
      )}

      <Field t={t} required label={t.s5_nmpa}
        error={errors.nmpa && t.err_required(t.s5_nmpa)}>
        <ChoiceGrid
          options={[
            { value: "yes", label: t.s5_nmpa_yes },
            { value: "no", label: t.s5_nmpa_no },
            { value: "progress", label: t.s5_nmpa_progress },
          ]}
          value={data.nmpa || ""}
          onChange={(v) => update("nmpa", v)}
        />
      </Field>

      <Field t={t} required label={t.s5_packaging}
        error={errors.china_packaging && t.err_required(t.s5_packaging)}>
        <ChoiceGrid
          options={[
            { value: "yes", label: t.s5_packaging_yes },
            { value: "no", label: t.s5_packaging_no },
            { value: "discuss", label: t.s5_packaging_discuss },
          ]}
          value={data.china_packaging || ""}
          onChange={(v) => update("china_packaging", v)}
        />
      </Field>

      <Field t={t} required label={t.s5_kol}
        error={errors.kol_ready && t.err_required(t.s5_kol)}>
        <ChoiceGrid
          options={[
            { value: "yes", label: t.s5_kol_yes },
            { value: "no", label: t.s5_kol_no },
            { value: "info", label: t.s5_kol_info },
          ]}
          value={data.kol_ready || ""}
          onChange={(v) => update("kol_ready", v)}
        />
      </Field>

      <Field t={t} required label={t.s5_volume}
        error={errors.volume && t.err_required(t.s5_volume)}>
        <Select
          options={t.s5_volume_options}
          placeholder="—"
          value={data.volume || ""}
          onChange={(v) => update("volume", v)}
        />
      </Field>

      <Field t={t} required label={t.s5_role}
        error={errors.role && t.err_required(t.s5_role)}>
        <ChoiceGrid
          options={t.s5_role_options}
          value={data.role || ""}
          onChange={(v) => update("role", v)}
        />
      </Field>
    </div>
  );
}

// ============================================================
// STEP 6 — Consent
// ============================================================
function Step6Consent({ data, update, errors, t, onOpenPrivacy }) {
  return (
    <div className="field-stack">
      {/* PDPA */}
      <div>
        <Choice
          kind="checkbox"
          checked={!!data.pdpa_consent}
          onChange={(v) => update("pdpa_consent", v)}
        >
          {t.s6_pdpa_label}
          <span className="field-required" style={{marginLeft: 8}}>{t.required}</span>
        </Choice>
        <div className="body-sm" style={{marginTop: 8, paddingLeft: 28}}>
          {t.s6_pdpa_body}
        </div>
        {errors.pdpa_consent && (
          <div className="field-error" style={{paddingLeft: 28}} role="alert">
            <i className="ti ti-alert-circle"></i>
            <span>{t.err_consent}</span>
          </div>
        )}
      </div>

      {/* PIPL */}
      <div>
        <Choice
          kind="checkbox"
          checked={!!data.pipl_consent}
          onChange={(v) => update("pipl_consent", v)}
        >
          {t.s6_pipl_label}
          <span className="field-required" style={{marginLeft: 8}}>{t.required}</span>
        </Choice>
        <div className="body-sm" style={{marginTop: 8, paddingLeft: 28}}>
          {t.s6_pipl_body}
        </div>
        <div style={{marginTop: 8, paddingLeft: 28}}>
          <TrustNote>{t.s6_pipl_trust}</TrustNote>
        </div>
        {errors.pipl_consent && (
          <div className="field-error" style={{paddingLeft: 28}} role="alert">
            <i className="ti ti-alert-circle"></i>
            <span>{t.err_consent}</span>
          </div>
        )}
      </div>

      <div style={{
        padding: "12px 14px",
        background: "var(--surface-container-low)",
        borderRadius: "var(--r)",
        display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center", justifyContent: "space-between"
      }}>
        <div>
          <div className="label-caps" style={{marginBottom: 2}}>{t.s6_dpo}</div>
          <div className="body-md">{t.s6_dpo_value}</div>
        </div>
        <Button variant="tertiary" icon="external-link" onClick={onOpenPrivacy}>{t.s6_privacy_link}</Button>
      </div>

      <Field
        t={t} required label={t.s6_signature} htmlFor="signature"
        help={!errors.signature ? t.s6_signature_help : undefined}
        error={
          errors.signature === "required" ? t.err_required(t.s6_signature) :
          errors.signature === "match" ? t.err_signature_match : undefined
        }
      >
        <TextInput
          id="signature"
          placeholder={t.s6_signature_ph}
          value={data.signature || ""}
          onChange={(v) => update("signature", v)}
        />
      </Field>

      <div className="body-sm">
        {t.s6_timestamp}: <span className="data-mono">{Format.timestamp(t === STRINGS.th ? "th" : "en")}</span>
      </div>
    </div>
  );
}

// ============================================================
// REVIEW
// ============================================================
function ReviewSection({ idx, label, onEdit, t, children, defaultOpen = true }) {
  const [open, setOpen] = useS(defaultOpen);
  return (
    <div className="review-section">
      <div className="review-section-head" onClick={() => setOpen(!open)} role="button" tabIndex={0}
        onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setOpen(!open); } }}
        aria-expanded={open}>
        <div className="review-section-title">
          <span className="review-section-num">{idx}</span>
          <span>{label}</span>
        </div>
        <div style={{display:"flex", gap: 4, alignItems: "center"}}>
          <Button variant="tertiary" size="sm" onClick={(e) => { e.stopPropagation(); onEdit(); }}>{t.edit}</Button>
          <IconButton icon={open ? "chevron-up" : "chevron-down"} label={open ? t.close : t.edit} onClick={(e) => { e.stopPropagation(); setOpen(!open); }} />
        </div>
      </div>
      {open && <div className="review-section-body">{children}</div>}
    </div>
  );
}
function ReviewRow({ label, value, t }) {
  const empty = value === undefined || value === null || value === "" ||
    (Array.isArray(value) && value.length === 0);
  return (
    <div className="review-row">
      <div className="review-row-label">{label}</div>
      <div className={`review-row-value ${empty ? "empty" : ""}`}>
        {empty ? t.review_empty : value}
      </div>
    </div>
  );
}

function Review({ data, t, jumpTo }) {
  const empty = t.review_empty;
  const phone = data.contact_phone ? `+66 ${Format.phoneTH(data.contact_phone)}` : "";
  const tax = data.tax_id ? Format.tax13(data.tax_id) : "";

  const filesLine = (files) => (files && files.length > 0)
    ? t.review_files(files.length) + " · " + files.map((f) => f.name).join(", ")
    : "";

  return (
    <div className="card">
      <div className="step-head">
        <div className="eyebrow"><span className="dot"></span><span>{t.step_review}</span></div>
        <h1 className="headline-md">{t.review_title}</h1>
        <p className="body-md" style={{marginTop: 6}}>{t.review_intro}</p>
      </div>

      <ReviewSection idx={1} label={t.s1_title} onEdit={() => jumpTo(0)} t={t}>
        <ReviewRow t={t} label={t.s1_company_th} value={data.company_th} />
        <ReviewRow t={t} label={t.s1_company_en} value={data.company_en} />
        <ReviewRow t={t} label={t.s1_company_cn} value={data.company_cn} />
        <ReviewRow t={t} label={t.s1_tax} value={tax ? <span className="data-mono">{tax}</span> : ""} />
        <ReviewRow t={t} label={t.s1_biz_type} value={data.biz_type} />
        <ReviewRow t={t} label={t.s1_address}
          value={[data.address, data.province, data.postcode].filter(Boolean).join(" · ")} />
        <ReviewRow t={t} label={t.s1_year} value={data.year ? <span className="data-mono">{data.year}</span> : ""} />
        <ReviewRow t={t} label={t.s1_employees} value={data.employees} />
        <ReviewRow t={t} label={t.s1_website} value={data.website} />
        <ReviewRow t={t} label={t.s1_facebook} value={data.facebook} />
        <ReviewRow t={t} label={t.s1_lineoa} value={data.lineoa} />
      </ReviewSection>

      <ReviewSection idx={2} label={t.s2_title} onEdit={() => jumpTo(1)} t={t}>
        <ReviewRow t={t} label={t.s2_name} value={data.contact_name} />
        <ReviewRow t={t} label={t.s2_position} value={data.contact_position} />
        <ReviewRow t={t} label={t.s2_phone} value={phone ? <span className="data-mono">{phone}</span> : ""} />
        <ReviewRow t={t} label={t.s2_email} value={data.contact_email} />
        <ReviewRow t={t} label={t.s2_line} value={data.contact_line} />
        <ReviewRow t={t} label={t.s2_wechat} value={data.contact_wechat} />
      </ReviewSection>

      <ReviewSection idx={3} label={t.s3_title} onEdit={() => jumpTo(2)} t={t}>
        <ReviewRow t={t} label={t.s3_cert} value={filesLine(data.doc_cert)} />
        <ReviewRow t={t} label={t.s3_logo} value={filesLine(data.doc_logo)} />
        <ReviewRow t={t} label={t.s3_id} value={filesLine(data.doc_id)} />
        <ReviewRow t={t} label={t.s3_licenses} value={filesLine(data.doc_licenses)} />
      </ReviewSection>

      <ReviewSection idx={4} label={t.s4_title} onEdit={() => jumpTo(3)} t={t}>
        <ReviewRow t={t} label={t.s4_title} value={data.products && data.products.length ? t.review_products(data.products.length) : ""} />
        {(data.products || []).map((p, i) => (
          <ReviewRow
            key={p.id}
            t={t}
            label={t.s4_product(i + 1)}
            value={p.name_th ? (
              <span>
                <strong style={{fontWeight: 500}}>{p.name_th}</strong>
                {p.category && <span className="body-sm" style={{marginLeft: 8}}>{p.category}</span>}
                {(p.images && p.images.length > 0) && <span className="body-sm" style={{marginLeft: 8}}>· {t.review_files(p.images.length)}</span>}
              </span>
            ) : ""}
          />
        ))}
      </ReviewSection>

      <ReviewSection idx={5} label={t.s5_title} onEdit={() => jumpTo(4)} t={t}>
        <ReviewRow t={t} label={t.s5_exported}
          value={data.exported === "yes" ? `${t.s5_exported_yes}${data.exported_channel ? " · " + data.exported_channel : ""}` :
                 data.exported === "no" ? t.s5_exported_no : ""} />
        <ReviewRow t={t} label={t.s5_nmpa}
          value={data.nmpa === "yes" ? t.s5_nmpa_yes : data.nmpa === "no" ? t.s5_nmpa_no : data.nmpa === "progress" ? t.s5_nmpa_progress : ""} />
        <ReviewRow t={t} label={t.s5_packaging}
          value={data.china_packaging === "yes" ? t.s5_packaging_yes : data.china_packaging === "no" ? t.s5_packaging_no : data.china_packaging === "discuss" ? t.s5_packaging_discuss : ""} />
        <ReviewRow t={t} label={t.s5_kol}
          value={data.kol_ready === "yes" ? t.s5_kol_yes : data.kol_ready === "no" ? t.s5_kol_no : data.kol_ready === "info" ? t.s5_kol_info : ""} />
        <ReviewRow t={t} label={t.s5_volume} value={data.volume} />
        <ReviewRow t={t} label={t.s5_role} value={data.role} />
      </ReviewSection>

      <ReviewSection idx={6} label={t.s6_title} onEdit={() => jumpTo(5)} t={t}>
        <ReviewRow t={t} label="PDPA" value={data.pdpa_consent ? <span><i className="ti ti-check" style={{color:"var(--on-success)", marginRight: 6}}></i>ยอมรับแล้ว</span> : ""} />
        <ReviewRow t={t} label="PIPL" value={data.pipl_consent ? <span><i className="ti ti-check" style={{color:"var(--on-success)", marginRight: 6}}></i>ยอมรับแล้ว</span> : ""} />
        <ReviewRow t={t} label={t.s6_signature} value={data.signature} />
      </ReviewSection>
    </div>
  );
}

// ============================================================
// SUCCESS
// ============================================================
// Deterministic QR-like SVG placeholder seeded from text. Renders 21x21 grid
// with 3 finder patterns at corners. Visually convincing as a QR code.
function QRPlaceholder({ seed, color = "#15181d" }) {
  const N = 21;
  // Simple deterministic hash
  let h = 0;
  for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;
  const rng = () => { h = (h * 1664525 + 1013904223) >>> 0; return (h & 0xffff) / 0x10000; };
  const cells = [];
  for (let y = 0; y < N; y++) {
    const row = [];
    for (let x = 0; x < N; x++) row.push(rng() > 0.52 ? 1 : 0);
    cells.push(row);
  }
  // Carve finder patterns 7x7 at three corners
  const drawFinder = (cx, cy) => {
    for (let y = 0; y < 7; y++) for (let x = 0; x < 7; x++) {
      const dx = cx + x, dy = cy + y;
      if (dx < 0 || dy < 0 || dx >= N || dy >= N) continue;
      const onRing = (x === 0 || x === 6 || y === 0 || y === 6);
      const onInner = (x >= 2 && x <= 4 && y >= 2 && y <= 4);
      cells[dy][dx] = (onRing || onInner) ? 1 : 0;
    }
    // Quiet zone
    for (let y = -1; y < 8; y++) for (let x = -1; x < 8; x++) {
      const dx = cx + x, dy = cy + y;
      if (dx < 0 || dy < 0 || dx >= N || dy >= N) continue;
      const inside = (x >= 0 && x <= 6 && y >= 0 && y <= 6);
      if (!inside) cells[dy][dx] = 0;
    }
  };
  drawFinder(0, 0);
  drawFinder(N - 7, 0);
  drawFinder(0, N - 7);

  const rects = [];
  for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
    if (cells[y][x]) rects.push(<rect key={`${x},${y}`} x={x} y={y} width="1" height="1" />);
  }
  return (
    <svg className="qr-svg" viewBox={`0 0 ${N} ${N}`} role="img" aria-label="QR code">
      <g fill={color} shapeRendering="crispEdges">{rects}</g>
    </svg>
  );
}

function SuccessScreen({ registrationId, t, lang, onRestart }) {
  const [copied, setCopied] = useS(false);
  const copy = () => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(registrationId);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    }
  };
  return (
    <div className="card success-card step-in">
      <div className="success-icon" aria-hidden="true">
        <svg viewBox="0 0 24 24">
          <path className="check-path" d="M5 12l4.5 4.5L19 7" />
        </svg>
      </div>
      <h1 className="headline-md">{t.success_title}</h1>
      <p className="body-md" style={{marginTop: 8, color: "var(--on-surface-variant)"}}>{t.success_sub}</p>

      <div className="success-id-card">
        <div>
          <div className="success-id-label">{t.success_id_label}</div>
          <div className="success-id-value">{registrationId}</div>
        </div>
        <IconButton icon={copied ? "check" : "copy"} label="Copy" onClick={copy} />
      </div>

      <p className="body-sm">{t.success_reminder}</p>

      <div className="qr-row">
        <div className="qr-card">
          <div className="qr-card-head">
            <i className="ti ti-brand-wechat"></i>
            <span>{t.success_wechat}</span>
          </div>
          <QRPlaceholder seed={`wechat:thaihao:${registrationId}`} color="#07c160" />
          <div className="qr-card-id">@thaihao_official</div>
        </div>
        <div className="qr-card">
          <div className="qr-card-head">
            <i className="ti ti-brand-line"></i>
            <span>{t.success_line}</span>
          </div>
          <QRPlaceholder seed={`line:thaihao:${registrationId}`} color="#06c755" />
          <div className="qr-card-id">@thaihao</div>
        </div>
      </div>

      <div className="portal-hint">
        <i className="ti ti-info-circle"></i>
        <div>
          <div className="portal-hint-title">{t.portal_hint_title}</div>
          <div className="portal-hint-body">{t.portal_hint_body}</div>
        </div>
      </div>

      <div className="success-contacts" style={{marginTop: 24}}>
        <Button variant="secondary" size="sm" icon="printer" onClick={() => window.print()}>{t.success_print}</Button>
      </div>
    </div>
  );
}

// Expose
Object.assign(window, {
  Step1Company, Step2Contact, Step3Documents, Step4Products,
  Step5Readiness, Step6Consent, Review, SuccessScreen, ProductCard,
});
