// Campaign Builder — wizard with AI question generation
const { useState: useState_cb, useEffect: useEffect_cb } = React;

function Stepper({ step }) {
  const steps = [
    { n: 1, label: 'Jenis Riset' },
    { n: 2, label: 'Detail Campaign' },
    { n: 3, label: 'Pertanyaan AI' },
    { n: 4, label: 'Hadiah' },
    { n: 5, label: 'Publikasi' },
  ];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      {steps.map((s, i) => {
        const done = step > s.n, active = step === s.n;
        return (
          <React.Fragment key={s.n}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: done ? 'var(--primary)' : active ? 'var(--primary-50)' : 'var(--bg-2)',
                color: done ? 'white' : active ? 'var(--primary)' : 'var(--ink-3)',
                border: active ? '1.5px solid var(--primary)' : '1px solid var(--line)',
                display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600,
              }}>
                {done ? '✓' : s.n}
              </div>
              <span style={{ fontSize: 12.5, fontWeight: active ? 600 : 500, color: active ? 'var(--ink)' : 'var(--ink-3)' }}>
                {s.label}
              </span>
            </div>
            {i < steps.length - 1 && <div style={{ width: 24, height: 1, background: done ? 'var(--primary)' : 'var(--line-2)' }}></div>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Grouped region picker. Pulls catalog from window.INDONESIA_REGIONS
// (templates.jsx). Renders native <select> with optgroups; if user picks
// "Custom…" we swap to a text input so they can type a kabupaten/kecamatan.
function RegionPicker({ value, onChange }) {
  const groups = window.INDONESIA_REGIONS || [];
  const flat = window.INDONESIA_REGIONS_FLAT || [];
  const isInCatalog = !value || flat.includes(value);
  const [custom, setCustom] = useState_cb(!isInCatalog);

  if (custom) {
    return (
      <div style={{ display: 'flex', gap: 6 }}>
        <input
          className="input"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="cth. Kab. Sleman, Kec. Sukolilo, Sumbawa…"
          style={{ flex: 1 }}
          autoFocus
        />
        <button
          className="btn btn-ghost"
          onClick={() => { setCustom(false); onChange('Indonesia (Nasional)'); }}
          style={{ padding: '8px 10px', fontSize: 12 }}
          title="Kembali ke daftar"
        >
          <I.X size={14} />
        </button>
      </div>
    );
  }

  return (
    <select
      className="select"
      value={isInCatalog ? value : ''}
      onChange={(e) => {
        if (e.target.value === '__custom__') {
          setCustom(true);
          onChange('');
        } else {
          onChange(e.target.value);
        }
      }}
    >
      {!isInCatalog && <option value="">Pilih wilayah…</option>}
      {groups.map((g) => (
        <optgroup key={g.label} label={g.label}>
          {g.items.map((r) => <option key={r} value={r}>{r}</option>)}
        </optgroup>
      ))}
      <optgroup label="Lainnya">
        <option value="__custom__">✏️ Custom… (ketik manual)</option>
      </optgroup>
    </select>
  );
}

// Catalog of respondent profile fields the campaign owner can collect.
// Order here drives display order in both the builder and the responder.
const PROFILE_FIELD_CATALOG = [
  { key: 'respondentName', label: 'Nama lengkap',     hint: 'Untuk personalisasi laporan' },
  { key: 'phone',          label: 'Nomor HP / WhatsApp', hint: 'Untuk follow-up & klaim hadiah' },
  { key: 'ageRange',       label: 'Rentang umur',     hint: '18-24, 25-34, 35-44, 45+' },
  { key: 'gender',         label: 'Gender',           hint: 'perempuan / laki-laki / lainnya' },
  { key: 'education',      label: 'Pendidikan terakhir', hint: 'SD–S3' },
  { key: 'occupation',     label: 'Pekerjaan',        hint: 'Bebas teks' },
  { key: 'incomeRange',    label: 'Range income bulanan', hint: '<2jt, 2-5jt, 5-10jt, 10-20jt, >20jt' },
  { key: 'maritalStatus',  label: 'Status pernikahan', hint: 'single / menikah / bercerai / janda-duda' },
  { key: 'domicileCity',   label: 'Kota domisili',    hint: 'Tempat tinggal saat ini' },
  { key: 'originCity',     label: 'Kota asal',        hint: 'Untuk pola migrasi' },
];

function ProfileFieldsSection({ profileFields, setProfileFields }) {
  const [open, setOpen] = useState_cb(false);
  const enabledCount = Object.values(profileFields).filter((v) => v !== 'off').length;

  return (
    <div className="card" style={{ marginTop: 14, padding: 0, overflow: 'hidden' }}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        style={{
          width: '100%', padding: '14px 18px', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', gap: 12, background: 'transparent',
          border: 'none', cursor: 'pointer', textAlign: 'left',
        }}
      >
        <div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Profil Responden</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
            Pilih demografi yang dikumpulkan dari responden — {enabledCount} dari {PROFILE_FIELD_CATALOG.length} aktif
          </div>
        </div>
        <I.ChevronDown size={16} style={{
          color: 'var(--ink-3)',
          transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          transition: 'transform 150ms',
        }} />
      </button>

      {open && (
        <div style={{ padding: '0 18px 16px' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 12 }}>
            <b>Off</b> = tidak ditanyakan. <b>Optional</b> = boleh dikosongkan. <b>Required</b> = wajib diisi sebelum lanjut.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {PROFILE_FIELD_CATALOG.map((f) => {
              const cur = profileFields[f.key] ?? 'off';
              return (
                <div key={f.key} style={{
                  display: 'grid', gridTemplateColumns: '1fr auto',
                  alignItems: 'center', gap: 14, padding: '8px 0',
                  borderTop: '1px solid var(--line)',
                }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{f.label}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{f.hint}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 2, padding: 2, borderRadius: 8, background: 'var(--bg-2)' }}>
                    {['off', 'optional', 'required'].map((mode) => (
                      <button
                        key={mode}
                        type="button"
                        onClick={() => setProfileFields((s) => ({ ...s, [f.key]: mode }))}
                        style={{
                          padding: '4px 10px', fontSize: 11.5, borderRadius: 6,
                          border: 'none',
                          background: cur === mode ? 'var(--surface)' : 'transparent',
                          color: cur === mode
                            ? (mode === 'required' ? 'var(--danger)' : 'var(--primary)')
                            : 'var(--ink-3)',
                          fontWeight: cur === mode ? 600 : 500,
                          boxShadow: cur === mode ? '0 1px 2px rgba(0,0,0,0.05)' : 'none',
                          cursor: 'pointer', textTransform: 'capitalize',
                        }}
                      >
                        {mode}
                      </button>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// Catalog of research types — each maps to campaigns.kind on the backend
// and triggers different aggregation logic in /api/campaigns/:id/launch-suite.
// `aiHint` is appended to the AI generate-questions prompt so question style
// matches the study type (recall, gap, appeal, comparison, perception).
const RESEARCH_KINDS = [
  {
    id: 'top_of_mind',
    emoji: '🧠',
    name: 'Top of Mind',
    tagline: 'Seberapa kuat brand di kepala konsumen',
    accent: 'oklch(0.52 0.18 265)',
    bg: 'oklch(0.96 0.04 265)',
    when: 'Benchmarking awareness vs kompetitor',
    sample: 'Sebutkan 3 brand pertama yang muncul di pikiran',
    duration: '~2 menit',
    level: 'Pemula',
    aiHint: 'Fokus pada pertanyaan unaided recall + brand share + NPS.',
  },
  {
    id: 'market_gap',
    emoji: '🔍',
    name: 'Market Gap',
    tagline: 'Cari kebutuhan konsumen yang belum terpenuhi',
    accent: 'oklch(0.55 0.16 35)',
    bg: 'oklch(0.96 0.05 35)',
    when: 'Sebelum launch produk / brand baru',
    sample: 'Apa yang paling kamu cari tapi sulit didapat?',
    duration: '~3-5 menit',
    level: 'Menengah',
    aiHint: 'Banyak pertanyaan terbuka tentang frustration & unmet needs di kategori. Tambahkan choice questions tentang tingkat kepuasan terhadap pemain saat ini.',
  },
  {
    id: 'concept_test',
    emoji: '🧪',
    name: 'Concept Test',
    tagline: 'Validasi konsep produk/iklan sebelum launch',
    accent: 'oklch(0.55 0.16 145)',
    bg: 'oklch(0.96 0.05 145)',
    when: 'Sudah ada draft konsep, butuh feedback',
    sample: 'Seberapa menarik konsep ini untuk kamu? (0-10)',
    duration: '~3-4 menit',
    level: 'Menengah',
    aiHint: 'Fokus pada appeal scale (0-10), purchase intent (choice), dan willingness-to-pay (open). Hindari pertanyaan recall.',
  },
  {
    id: 'brand_name',
    emoji: '🏷️',
    name: 'Brand Name Test',
    tagline: 'Bandingkan beberapa kandidat nama / logo',
    accent: 'oklch(0.50 0.18 305)',
    bg: 'oklch(0.95 0.05 305)',
    when: 'Pra-launch dengan 2-3+ kandidat',
    sample: 'Mana nama yang paling cocok untuk brand kopi premium?',
    duration: '~2-3 menit',
    level: 'Pemula',
    aiHint: 'Banyak choice questions yang membandingkan kandidat satu per satu (head-to-head). Setiap kandidat tampil di 2-3 pertanyaan dengan framing berbeda (kesan, kecocokan, preferensi).',
  },
  {
    id: 'perception',
    emoji: '🎯',
    name: 'Brand Perception',
    tagline: 'Map persepsi brand vs target positioning',
    accent: 'oklch(0.45 0.18 230)',
    bg: 'oklch(0.95 0.06 230)',
    when: 'Audit periodik untuk reposisioning',
    sample: 'Seberapa premium brand ini? (0-10)',
    duration: '~4-5 menit',
    level: 'Lanjutan',
    aiHint: 'Pakai banyak scale 0-10 untuk atribut perception (premium, hangat, terpercaya, modern, lokal, ramah, dll). 6-8 atribut. Tambahkan 1 pertanyaan terbuka di akhir.',
  },
  {
    id: 'pmf',
    emoji: '🚀',
    name: 'Product-Market Fit',
    tagline: 'Sean Ellis test — apakah produk sudah klop dengan pasar',
    accent: 'oklch(0.55 0.18 165)',
    bg: 'oklch(0.95 0.06 165)',
    when: 'Sudah ada user aktif, mau tahu apakah PMF tercapai',
    sample: 'Seberapa kecewa kalau tidak bisa pakai lagi?',
    duration: '~3-4 menit',
    level: 'Menengah',
    aiHint: 'Test PMF klasik Sean Ellis. Pakai EXACTLY 4-5 pertanyaan dalam urutan: (1) choice "Bagaimana perasaan kamu kalau tidak bisa pakai [brand] lagi?" dengan 3 opsi PERSIS: ["Sangat kecewa", "Sedikit kecewa", "Tidak kecewa"] — INI WAJIB karena dipakai untuk hitung PMF score. (2) open "Tipe orang seperti apa yang paling cocok pakai [brand]?" (3) open "Apa benefit utama yang kamu dapat dari [brand]?" (4) open "Bagaimana kami bisa improve [brand] untuk kamu?". JANGAN tambah pertanyaan unaided recall, NPS, atau brand share. Hindari skala 0-10.',
  },
];

function KindStep({ kind, setKind, onNext }) {
  return (
    <div className="fade-in">
      <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>
        Mau riset apa hari ini?
      </h2>
      <p style={{ margin: '0 0 24px', color: 'var(--ink-3)', fontSize: 13.5 }}>
        Pilih jenis riset yang paling cocok dengan tujuanmu — AI akan menyesuaikan pertanyaan & analitik otomatis.
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
        {RESEARCH_KINDS.map((k) => {
          const active = kind === k.id;
          return (
            <button
              key={k.id}
              onClick={() => setKind(k.id)}
              style={{
                position: 'relative', textAlign: 'left', cursor: 'pointer',
                background: 'var(--surface)',
                border: active ? `1.5px solid ${k.accent}` : '1px solid var(--line)',
                borderRadius: 14, padding: 18,
                boxShadow: active ? `0 0 0 4px ${k.accent.replace(')', ' / 0.10)')}` : 'var(--shadow-sm)',
                display: 'flex', flexDirection: 'column', gap: 10,
                transition: 'all 140ms',
                minHeight: 220,
              }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.boxShadow = 'var(--shadow-md)'; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.boxShadow = 'var(--shadow-sm)'; }}
            >
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 12,
                  background: k.bg, display: 'grid', placeItems: 'center',
                  fontSize: 26, lineHeight: 1, flexShrink: 0,
                }}>{k.emoji}</div>
                {active && (
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: k.accent, color: 'white',
                    display: 'grid', placeItems: 'center',
                  }}><I.Check size={13} /></div>
                )}
              </div>

              <div>
                <div style={{ fontSize: 15.5, fontWeight: 700, lineHeight: 1.2 }}>{k.name}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.45 }}>{k.tagline}</div>
              </div>

              <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11.5, color: 'var(--ink-3)' }}>
                  <I.Crosshair size={11} style={{ color: k.accent, flexShrink: 0 }} />
                  <span style={{ flex: 1 }}>{k.when}</span>
                </div>
                <div style={{ display: 'flex', gap: 8, fontSize: 10.5, color: 'var(--ink-3)' }}>
                  <span className="badge" style={{ fontSize: 10, padding: '2px 7px' }}>⏱ {k.duration}</span>
                  <span className="badge" style={{ fontSize: 10, padding: '2px 7px' }}>📊 {k.level}</span>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 24 }}>
        <button className="btn btn-primary" onClick={onNext}>
          Lanjut ke Detail <I.ArrowRight size={14} />
        </button>
      </div>
    </div>
  );
}

function CampaignBuilder({ onPublished } = {}) {
  const [step, setStep] = useState_cb(1);
  // Research kind picked at step 1 — drives campaign.kind on the backend
  // and biases the AI prompt. Catalog defined in RESEARCH_KINDS.
  const [kind, setKind] = useState_cb('top_of_mind');
  // Brand is now picked from the user's brand list (loaded on mount). The
  // freetext input is gone — users edit brand details on the Brand Profile
  // screen, and the campaign just references the chosen brand by id.
  const [availableBrands, setAvailableBrands] = useState_cb([]);
  const [brandId, setBrandId] = useState_cb('');
  const [industry, setIndustry] = useState_cb('F&B — Coffee Shop');
  const [region, setRegion] = useState_cb('Surabaya');
  const [competitors, setCompetitors] = useState_cb(['Kopi Janji Manis', 'Tomoro Coffee', 'Fore Coffee']);
  const [newComp, setNewComp] = useState_cb('');
  const [generating, setGenerating] = useState_cb(false);
  const [generated, setGenerated] = useState_cb(false);
  const [questions, setQuestions] = useState_cb([]);
  const [editingIdx, setEditingIdx] = useState_cb(null);
  const [genStep, setGenStep] = useState_cb(0);
  // Default reward: pulls from window.__pinnedReward if user pinned one in
  // the Rewards screen, else use a sensible default. The picker in step 3
  // lets the user swap presets at any time.
  const [reward, setReward] = useState_cb(() => {
    const pin = window.__pinnedReward;
    if (pin) return { rewardType: pin.type, valueOrLink: pin.valueOrLink, quota: pin.quota || 0, presetId: pin.id };
    return { rewardType: 'voucher', valueOrLink: 'Voucher Rp 10.000', quota: 2000, presetId: null };
  });
  // Profile fields collected from respondents. Map of key → 'off' | 'optional' | 'required'.
  // Default: ageRange + gender optional (legacy behavior); everything else off.
  const [profileFields, setProfileFields] = useState_cb({
    respondentName: 'off',
    phone: 'off',
    ageRange: 'optional',
    gender: 'optional',
    education: 'off',
    occupation: 'off',
    incomeRange: 'off',
    maritalStatus: 'off',
    domicileCity: 'off',
    originCity: 'off',
  });
  const [error, setError] = useState_cb(null);

  // Convert profileFields map → backend shape (only enabled fields, with required flag).
  const respondentFieldsPayload = Object.entries(profileFields)
    .filter(([, mode]) => mode !== 'off')
    .map(([key, mode]) => ({ key, required: mode === 'required' }));

  React.useEffect(() => {
    window.api.listBrands()
      .then(({ brands }) => {
        setAvailableBrands(brands || []);
        const primary = brands?.find((b) => b.isPrimary) ?? brands?.[0];
        if (primary) {
          setBrandId(primary.id);
          if (primary.category) setIndustry(primary.category);
        }
      })
      .catch(() => setAvailableBrands([]));
  }, []);

  const selectedBrand = availableBrands.find((b) => b.id === brandId);
  const brand = selectedBrand?.name ?? '';

  const addCompetitor = () => {
    if (newComp.trim() && !competitors.includes(newComp.trim())) {
      setCompetitors([...competitors, newComp.trim()]);
      setNewComp('');
    }
  };

  const stages = [
    `Menganalisis konteks ${industry}…`,
    'Menyusun framework Top of Mind…',
    `Memetakan ${competitors.length} kompetitor…`,
    'Membuat draf pertanyaan…',
  ];

  // Real AI call to /api/ai/generate-questions, with the same staged loading
  // animation the design uses so the visual feel doesn't change.
  const generate = async () => {
    setGenerating(true);
    setGenerated(false);
    setQuestions([]);
    setGenStep(0);
    setError(null);

    let result;
    try {
      // Kick off the network call and the staged animation in parallel —
      // whichever takes longer wins.
      const apiCall = window.api.generateQuestions({ brand, brandId, competitors, industry, region, kind });
      for (let i = 0; i < stages.length; i++) {
        setGenStep(i);
        await new Promise((r) => setTimeout(r, 450));
      }
      result = await apiCall;
    } catch (err) {
      setGenerating(false);
      setError(err.message || 'Gagal generate pertanyaan');
      return;
    }

    const incoming = (result.questions || []).map((q) => ({
      type: q.type,
      text: q.text,
      options: q.options,
      required: q.required,
      aiGenerated: true,
      hint: q.type === 'open' ? 'Top of Mind awareness — pertanyaan inti' : undefined,
    }));

    for (const q of incoming) {
      await new Promise((r) => setTimeout(r, 280));
      setQuestions((prev) => [...prev, q]);
    }
    setGenerating(false);
    setGenerated(true);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <TopBar
        title="Campaign Baru"
        subtitle="Susun survei Top of Mind dengan bantuan AI dalam 4 langkah"
        right={<button className="btn btn-ghost"><I.X size={14} />Batal</button>}
      />

      <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
        <Stepper step={step} />
      </div>

      <div className="scroll" style={{ flex: 1, overflow: 'auto', padding: 24, background: 'var(--bg)' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>

          {step === 1 && (
            <KindStep kind={kind} setKind={setKind} onNext={() => setStep(2)} />
          )}

          {step === 2 && (
            <div className="fade-in">
              <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Ceritakan tentang bisnismu</h2>
              <p style={{ margin: '0 0 20px', color: 'var(--ink-3)', fontSize: 13.5 }}>
                Informasi ini membantu AI menyusun pertanyaan yang relevan dengan industri & kompetitormu.
              </p>

              <div className="card" style={{ padding: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <label className="label">Brand</label>
                  {availableBrands.length === 0 ? (
                    <div style={{ fontSize: 13, color: 'var(--ink-3)', padding: '10px 12px', border: '1px dashed var(--line-2)', borderRadius: 8 }}>
                      Belum ada brand. Buka <b>Brand Profile</b> di sidebar untuk membuat satu.
                    </div>
                  ) : availableBrands.length === 1 ? (
                    <div className="input" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'var(--bg-2)', cursor: 'default' }}>
                      <span style={{ fontWeight: 500 }}>{availableBrands[0].name}</span>
                      <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{availableBrands[0].category || ''}</span>
                    </div>
                  ) : (
                    <select className="select" value={brandId} onChange={(e) => {
                      setBrandId(e.target.value);
                      const b = availableBrands.find((x) => x.id === e.target.value);
                      if (b?.category) setIndustry(b.category);
                    }}>
                      {availableBrands.map((b) => (
                        <option key={b.id} value={b.id}>{b.name}{b.isPrimary ? ' · utama' : ''}</option>
                      ))}
                    </select>
                  )}
                </div>
                <div>
                  <label className="label">Kategori industri</label>
                  <select className="select" value={industry} onChange={(e) => setIndustry(e.target.value)}>
                    <option>F&B — Coffee Shop</option>
                    <option>F&B — Restoran</option>
                    <option>Retail Fashion</option>
                    <option>E-commerce</option>
                    <option>Telco / Operator</option>
                    <option>Banking / Fintech</option>
                  </select>
                </div>
                <div>
                  <label className="label">Target wilayah</label>
                  <RegionPicker value={region} onChange={setRegion} />
                </div>
                <div>
                  <label className="label">Periode survei</label>
                  <input className="input" defaultValue="3 Mei 2026 — 31 Mei 2026" />
                </div>

                <div style={{ gridColumn: '1 / -1' }}>
                  <label className="label">Kompetitor utama</label>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
                    {competitors.map((c, i) => (
                      <span key={i} className="badge" style={{ padding: '6px 10px', fontSize: 12.5 }}>
                        {c}
                        <button onClick={() => setCompetitors(competitors.filter((_, j) => j !== i))}
                                style={{ border: 'none', background: 'none', padding: 0, color: 'var(--ink-3)', cursor: 'pointer', display: 'flex' }}>
                          <I.X size={12} />
                        </button>
                      </span>
                    ))}
                  </div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input className="input" value={newComp} onChange={(e) => setNewComp(e.target.value)}
                      onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addCompetitor())}
                      placeholder="Tambahkan nama kompetitor lalu tekan Enter" style={{ flex: 1 }} />
                    <button className="btn btn-soft" onClick={addCompetitor}><I.Plus size={14} />Tambah</button>
                  </div>
                </div>
              </div>

              <ProfileFieldsSection profileFields={profileFields} setProfileFields={setProfileFields} />

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
                <button className="btn btn-ghost" onClick={() => setStep(1)}>
                  <I.ChevronLeft size={14} />Ganti jenis riset
                </button>
                <button className="btn btn-primary" onClick={() => setStep(3)}>
                  Lanjut ke Pertanyaan <I.ArrowRight size={14} />
                </button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="fade-in">
              <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16 }}>
                <div>
                  <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Pertanyaan Survei</h2>
                  <p style={{ margin: 0, color: 'var(--ink-3)', fontSize: 13.5 }}>Biarkan AI buat draf, atau tulis manual.</p>
                </div>
                {!generating && (
                  <button className="btn btn-primary" onClick={generate} style={{
                    background: generated ? 'var(--surface)' : 'var(--primary)',
                    color: generated ? 'var(--primary)' : 'white',
                    border: generated ? '1px solid oklch(0.88 0.06 265)' : 'none',
                  }}>
                    <I.Sparkle size={14} />{generated ? 'Generate Ulang' : 'Generate dengan AI'}
                  </button>
                )}
              </div>

              {!generating && questions.length === 0 && (
                <div className="card" style={{
                  padding: 40, textAlign: 'center', borderStyle: 'dashed',
                  background: 'linear-gradient(180deg, var(--primary-50), var(--surface))',
                }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: 16, margin: '0 auto 14px',
                    background: 'linear-gradient(135deg, var(--primary), oklch(0.62 0.20 290))',
                    display: 'grid', placeItems: 'center', color: 'white',
                    boxShadow: '0 8px 24px -8px oklch(0.52 0.18 265 / 0.50)',
                  }}><I.Sparkle size={26} /></div>
                  <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 6 }}>Mulai dengan AI</div>
                  <div style={{ color: 'var(--ink-3)', fontSize: 13, maxWidth: 380, margin: '0 auto 18px' }}>
                    AI akan men-generate 5–7 pertanyaan Top of Mind yang dirancang khusus untuk <b style={{ color: 'var(--ink-2)' }}>{industry}</b> dan kompetitormu.
                  </div>
                  <button className="btn btn-primary" onClick={generate}>
                    <I.Sparkle size={14} />Generate Pertanyaan
                  </button>
                </div>
              )}

              {generating && (
                <div className="card" style={{ padding: 24 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 10,
                      background: 'linear-gradient(135deg, var(--primary), oklch(0.62 0.20 290))',
                      display: 'grid', placeItems: 'center', color: 'white',
                      animation: 'pulse 1.4s ease-in-out infinite',
                    }}><I.Sparkle size={18} /></div>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>AI sedang berpikir…</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Biasanya selesai dalam 5–8 detik</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {stages.map((s, i) => (
                      <div key={i} style={{
                        display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
                        color: i <= genStep ? 'var(--ink)' : 'var(--ink-4)',
                        opacity: i <= genStep ? 1 : 0.5,
                        transition: 'all 200ms',
                      }}>
                        {i < genStep ? (
                          <I.Check size={14} style={{ color: 'oklch(0.55 0.15 155)' }} />
                        ) : i === genStep ? (
                          <span style={{
                            width: 14, height: 14, border: '2px solid var(--primary)',
                            borderTopColor: 'transparent', borderRadius: '50%',
                            animation: 'spin 0.7s linear infinite',
                          }}></span>
                        ) : (
                          <span style={{ width: 14, height: 14, borderRadius: '50%', border: '1.5px solid var(--line-2)' }}></span>
                        )}
                        <span>{s}</span>
                      </div>
                    ))}
                  </div>
                  {questions.length > 0 && (
                    <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>
                        Draf pertanyaan ({questions.length})
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {questions.map((q, i) => <QuestionRow key={i} q={q} idx={i} animated />)}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {!generating && questions.length > 0 && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {questions.map((q, i) => (
                    editingIdx === i ? (
                      <QuestionEditor
                        key={i}
                        idx={i}
                        question={q}
                        onSave={(updated) => {
                          setQuestions((prev) => prev.map((p, pi) => (pi === i ? updated : p)));
                          setEditingIdx(null);
                        }}
                        onCancel={() => setEditingIdx(null)}
                      />
                    ) : (
                      <QuestionRow
                        key={i}
                        q={q}
                        idx={i}
                        editable
                        onEdit={() => setEditingIdx(i)}
                        onDelete={() => {
                          if (window.confirm('Hapus pertanyaan ini?')) {
                            setQuestions((prev) => prev.filter((_, pi) => pi !== i));
                          }
                        }}
                      />
                    )
                  ))}
                  <button
                    className="btn btn-ghost"
                    style={{ alignSelf: 'flex-start', marginTop: 4 }}
                    onClick={() => {
                      setQuestions((prev) => {
                        const next = [
                          ...prev,
                          { type: 'open', text: '', options: undefined, required: true, aiGenerated: false },
                        ];
                        setEditingIdx(next.length - 1);
                        return next;
                      });
                    }}
                  >
                    <I.Plus size={14} />Tambah pertanyaan manual
                  </button>
                </div>
              )}

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
                <button className="btn btn-ghost" onClick={() => setStep(2)}><I.ChevronLeft size={14} />Kembali</button>
                <button className="btn btn-primary" disabled={questions.length === 0} onClick={() => setStep(4)}
                        style={{ opacity: questions.length === 0 ? 0.5 : 1 }}>
                  Lanjut ke Hadiah <I.ArrowRight size={14} />
                </button>
              </div>
            </div>
          )}

          {step === 4 && (
            <RewardStep
              reward={reward}
              setReward={setReward}
              onBack={() => setStep(3)}
              onNext={() => setStep(5)}
            />
          )}
          {step === 5 && (
            <PublishStep
              onBack={() => setStep(4)}
              brand={brand}
              brandId={brandId}
              kind={kind}
              industry={industry}
              region={region}
              competitors={competitors}
              questions={questions}
              reward={reward}
              respondentFields={respondentFieldsPayload}
              onPublished={onPublished}
            />
          )}
          {error && step === 3 && (
            <div style={{ marginTop: 12, padding: 10, borderRadius: 8, background: 'var(--danger-soft)', color: 'var(--danger)', fontSize: 12.5 }}>
              {error}
            </div>
          )}

        </div>
      </div>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }
      `}</style>
    </div>
  );
}

function QuestionRow({ q, idx, editable, animated, onEdit, onDelete }) {
  const types = {
    open:     { label: 'Pertanyaan Terbuka', color: 'var(--primary)',       bg: 'var(--primary-50)' },
    choice:   { label: 'Pilihan Ganda',      color: 'oklch(0.42 0.12 155)',  bg: 'var(--accent-soft)' },
    scale:    { label: 'Skala 0-10',         color: 'oklch(0.42 0.12 155)', bg: 'var(--success-soft)' },
    location: { label: 'Lokasi',             color: 'oklch(0.45 0.13 25)',  bg: 'oklch(0.96 0.04 25)' },
  };
  const t = types[q.type] || { label: (q.type || 'lainnya').toUpperCase(), color: 'var(--ink-2)', bg: 'var(--bg-2)' };
  return (
    <div className={animated ? 'slide-up' : ''} style={{
      padding: 14, background: 'var(--surface)', border: '1px solid var(--line)',
      borderRadius: 12, display: 'flex', gap: 12,
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 8, flexShrink: 0,
        background: 'var(--bg-2)', color: 'var(--ink-3)', display: 'grid', placeItems: 'center',
        fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
      }}>{idx + 1}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 10.5, padding: '2px 7px', borderRadius: 4, background: t.bg, color: t.color, fontWeight: 600, letterSpacing: '0.02em', textTransform: 'uppercase' }}>
            {t.label}
          </span>
          {q.hint && <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{q.hint}</span>}
        </div>
        <div style={{ fontSize: 13.5, lineHeight: 1.45, color: 'var(--ink)' }}>{q.text}</div>
        {q.options && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 6 }}>
            {q.options.map((o, i) => (
              <span key={i} className="badge" style={{ fontSize: 11, padding: '2px 7px' }}>{o}</span>
            ))}
          </div>
        )}
      </div>
      {editable && (
        <div style={{ display: 'flex', gap: 4, alignSelf: 'flex-start' }}>
          <button className="btn btn-ghost" style={{ padding: 6 }} title="Edit" onClick={onEdit}>
            <I.Edit size={13} />
          </button>
          <button className="btn btn-ghost" style={{ padding: 6 }} title="Hapus" onClick={onDelete}>
            <I.Trash size={13} />
          </button>
        </div>
      )}
    </div>
  );
}

// Inline editor for a single question. Used in step 2 when the user clicks
// the pencil on a row, or "Tambah pertanyaan manual". Saves back to the
// parent's questions array via onSave; closes via onCancel.
function QuestionEditor({ idx, question, onSave, onCancel }) {
  const [type, setType] = useState_cb(question.type || 'open');
  const [text, setText] = useState_cb(question.text || '');
  const [options, setOptions] = useState_cb(
    Array.isArray(question.options) ? question.options.join('\n') : '',
  );
  const [required, setRequired] = useState_cb(question.required !== false);

  const typeOptions = [
    { id: 'open',     label: 'Terbuka' },
    { id: 'choice',   label: 'Pilihan Ganda' },
    { id: 'scale',    label: 'Skala 0-10' },
    { id: 'location', label: 'Lokasi' },
  ];

  const save = () => {
    if (!text.trim()) return;
    const opts = type === 'choice'
      ? options.split('\n').map((s) => s.trim()).filter(Boolean)
      : undefined;
    onSave({
      type,
      text: text.trim(),
      options: opts && opts.length > 0 ? opts : undefined,
      required,
      aiGenerated: question.aiGenerated === true,
    });
  };

  return (
    <div className="card" style={{
      padding: 14, border: '1.5px solid var(--primary)',
      boxShadow: '0 0 0 4px oklch(0.52 0.18 265 / 0.10)',
      display: 'flex', gap: 12,
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 8, flexShrink: 0,
        background: 'var(--primary-50)', color: 'var(--primary)',
        display: 'grid', placeItems: 'center',
        fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
      }}>{idx + 1}</div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-2)', borderRadius: 8 }}>
            {typeOptions.map((t) => (
              <button
                key={t.id}
                onClick={() => setType(t.id)}
                style={{
                  padding: '4px 10px', fontSize: 11.5, borderRadius: 6, border: 'none',
                  background: type === t.id ? 'var(--surface)' : 'transparent',
                  color: type === t.id ? 'var(--primary)' : 'var(--ink-3)',
                  fontWeight: type === t.id ? 600 : 500,
                  boxShadow: type === t.id ? '0 1px 2px rgba(0,0,0,0.05)' : 'none',
                  cursor: 'pointer',
                }}
              >{t.label}</button>
            ))}
          </div>
          <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-2)', cursor: 'pointer', marginLeft: 'auto' }}>
            <input type="checkbox" checked={required} onChange={(e) => setRequired(e.target.checked)} />
            Wajib
          </label>
        </div>

        <textarea
          className="textarea"
          rows={2}
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Tulis pertanyaan untuk responden…"
          autoFocus
        />

        {type === 'choice' && (
          <div>
            <label className="label" style={{ marginBottom: 4 }}>Pilihan jawaban (satu per baris)</label>
            <textarea
              className="textarea"
              rows={4}
              value={options}
              onChange={(e) => setOptions(e.target.value)}
              placeholder={'Kopi Kenanga\nJanji Manis\nTomoro Coffee\nLainnya'}
            />
          </div>
        )}

        <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onCancel} style={{ padding: '6px 12px', fontSize: 12.5 }}>Batal</button>
          <button
            className="btn btn-primary"
            onClick={save}
            disabled={!text.trim() || (type === 'choice' && options.split('\n').filter((s) => s.trim()).length < 2)}
            style={{ padding: '6px 12px', fontSize: 12.5 }}
          >
            <I.Check size={13} /> Simpan
          </button>
        </div>
      </div>
    </div>
  );
}

function RewardStep({ reward, setReward, onBack, onNext }) {
  const type = reward.rewardType;
  const setType = (rewardType) => setReward({ ...reward, rewardType, presetId: null });
  const types = [
    { id: 'voucher', icon: '🎟', label: 'Voucher Digital', sub: 'Kode unik dari Tokopedia, Shopee, GoFood' },
    { id: 'e_wallet', icon: '💸', label: 'Cashback E-Wallet', sub: 'Otomatis ke OVO, GoPay, atau DANA' },
    { id: 'promo_code', icon: '🏷', label: 'Kode Promo', sub: 'Diskon di outlet brand sendiri' },
    { id: 'digital_access', icon: '⭐', label: 'Poin Loyalitas', sub: 'Tambah ke akun member existing' },
  ];
  // Default fallback per type — mirip REWARD_TYPE_DEFAULTS di app-shell.jsx,
  // dipakai untuk render visual custom preset yang gak punya bg/color sendiri.
  const TYPE_FB = {
    voucher:        { emoji: '🎟️', bg: 'oklch(0.96 0.04 145)', color: 'oklch(0.42 0.14 145)' },
    e_wallet:       { emoji: '💸', bg: 'oklch(0.96 0.05 25)',  color: 'oklch(0.55 0.16 25)'  },
    promo_code:     { emoji: '🏷️', bg: 'oklch(0.96 0.05 35)',  color: 'oklch(0.55 0.16 35)'  },
    digital_access: { emoji: '⭐', bg: 'oklch(0.95 0.05 265)', color: 'oklch(0.45 0.18 265)' },
  };

  // Custom presets per workspace (bisa kosong saat belum bikin).
  const [customPresets, setCustomPresets] = useState_cb([]);
  React.useEffect(() => {
    window.api.listRewardPresets()
      .then((r) => setCustomPresets(r.presets || []))
      .catch(() => setCustomPresets([]));
  }, []);

  // Gabungkan: custom dulu, lalu built-in. Normalisasi ke shape yang sama.
  const builtIn = (window.REWARD_PRESETS || []).map((p) => ({
    id: p.id, name: p.name, value: p.value, valueOrLink: p.valueOrLink,
    type: p.type, quota: p.quota || 0, emoji: p.emoji, bg: p.bg, color: p.color, tag: p.tag,
  }));
  const customNormalized = customPresets.map((p) => {
    const fb = TYPE_FB[p.rewardType] || TYPE_FB.voucher;
    return {
      id: p.id,
      name: p.name,
      value: p.valueOrLink,
      valueOrLink: p.valueOrLink,
      type: p.rewardType,
      quota: p.quota || 0,
      emoji: p.emoji || fb.emoji,
      bg: fb.bg,
      color: fb.color,
      tag: 'Saya',
    };
  });
  const presets = [...customNormalized, ...builtIn];

  const applyPreset = (p) =>
    setReward({ rewardType: p.type, valueOrLink: p.valueOrLink, quota: p.quota || 0, presetId: p.id });

  return (
    <div className="fade-in">
      <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>Hadiah untuk Responden</h2>
      <p style={{ margin: '0 0 20px', color: 'var(--ink-3)', fontSize: 13.5 }}>
        Hadiah otomatis muncul setelah responden submit. Survei dengan hadiah biasanya selesai 3× lebih banyak.
      </p>

      {/* Preset gallery — horizontal scroll on small viewports */}
      <div className="card" style={{ padding: 16, marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Pilih Hadiah Siap Pakai</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
              {reward.presetId
                ? 'Sudah pakai preset — kamu masih bisa tweak detail di bawah.'
                : 'Klik kartu untuk apply. Atau scroll ke bawah untuk custom.'}
            </div>
          </div>
        </div>
        <div className="scroll" style={{
          display: 'grid', gridAutoFlow: 'column', gridAutoColumns: '230px',
          gap: 10, overflowX: 'auto', padding: '4px 2px 12px',
        }}>
          {presets.map((p) => {
            const active = reward.presetId === p.id;
            return (
              <button
                key={p.id}
                onClick={() => applyPreset(p)}
                style={{
                  textAlign: 'left', cursor: 'pointer',
                  background: 'var(--surface)',
                  border: active ? '1.5px solid var(--primary)' : '1px solid var(--line)',
                  borderRadius: 12, padding: 12,
                  boxShadow: active ? '0 0 0 4px oklch(0.52 0.18 265 / 0.10)' : 'none',
                  display: 'flex', flexDirection: 'column', gap: 8,
                  transition: 'all 140ms',
                }}
              >
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 10,
                    background: p.bg, color: p.color,
                    display: 'grid', placeItems: 'center',
                    fontSize: 19, lineHeight: 1, flexShrink: 0,
                  }}>{p.emoji}</div>
                  {p.tag && (
                    <span style={{
                      fontSize: 9.5, padding: '2px 6px', borderRadius: 999, fontWeight: 600,
                      background: p.bg, color: p.color, letterSpacing: '0.02em',
                    }}>{p.tag}</span>
                  )}
                </div>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.3 }}>{p.name}</div>
                  <div className="mono" style={{ fontSize: 12, color: p.color, fontWeight: 700, marginTop: 2 }}>{p.value}</div>
                </div>
                {active && (
                  <span style={{ fontSize: 10.5, color: 'var(--primary)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <I.Check size={11} /> Aktif
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 16 }}>
        {types.map((t) => (
          <button key={t.id} onClick={() => setType(t.id)} style={{
            padding: 16, textAlign: 'left',
            background: 'var(--surface)',
            border: type === t.id ? '1.5px solid var(--primary)' : '1px solid var(--line)',
            borderRadius: 12, cursor: 'pointer',
            boxShadow: type === t.id ? '0 0 0 4px oklch(0.52 0.18 265 / 0.10)' : 'none',
            transition: 'all 140ms', display: 'flex', gap: 12, alignItems: 'flex-start',
          }}>
            <div style={{ fontSize: 22, lineHeight: 1 }}>{t.icon}</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13.5 }}>{t.label}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>{t.sub}</div>
            </div>
            {type === t.id && (
              <I.Check size={16} style={{ color: 'var(--primary)', marginLeft: 'auto', flexShrink: 0 }} />
            )}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 20 }}>
        <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>Detail Hadiah</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <div>
            <label className="label">Nilai per responden</label>
            <input
              className="input"
              value={reward.valueOrLink || ''}
              onChange={(e) => setReward({ ...reward, valueOrLink: e.target.value })}
              placeholder="cth. Voucher Rp 10.000"
            />
          </div>
          <div>
            <label className="label">Kuota total</label>
            <input
              className="input"
              type="number"
              min="0"
              value={reward.quota}
              onChange={(e) => setReward({ ...reward, quota: Number(e.target.value) || 0 })}
              placeholder="2000"
            />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label className="label">Pesan setelah klaim</label>
            <textarea className="textarea" rows="2" defaultValue="Terima kasih sudah membantu Kopi Kenanga jadi lebih baik! Voucher Anda akan dikirim ke nomor WhatsApp dalam 5 menit." />
          </div>
        </div>

        <div style={{ marginTop: 14, padding: 12, borderRadius: 10, background: 'var(--bg-2)', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, color: 'var(--ink-2)' }}>
          <I.Lightning size={14} style={{ color: 'oklch(0.65 0.15 75)', flexShrink: 0 }} />
          <span>Estimasi total: <b className="mono">Rp 20.000.000</b> · sudah termasuk biaya distribusi otomatis (2.5%).</span>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
        <button className="btn btn-ghost" onClick={onBack}><I.ChevronLeft size={14} />Kembali</button>
        <button className="btn btn-primary" onClick={onNext}>Lanjut ke Publikasi <I.ArrowRight size={14} /></button>
      </div>
    </div>
  );
}

function PublishStep({ onBack, brand, brandId, kind, industry, region, competitors, questions, reward, respondentFields, onPublished }) {
  const [copied, setCopied] = React.useState(false);
  const [publishing, setPublishing] = React.useState(false);
  const [published, setPublished] = React.useState(null); // { id, slug, url }
  const [error, setError] = React.useState(null);

  const fullUrl = published ? `${window.location.origin}/survey/${published.slug}` : null;

  const copy = () => {
    if (!fullUrl) return;
    navigator.clipboard?.writeText(fullUrl).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  const publish = async () => {
    setPublishing(true);
    setError(null);
    try {
      // 1) create campaign
      // Title prefix mirrors the chosen kind so the dashboard list reads natural
      // (e.g. "Concept Test Kopi Kenanga", "Brand Perception Geprekin").
      const titlePrefix = ({
        top_of_mind: 'Brand Awareness',
        market_gap: 'Market Gap',
        concept_test: 'Concept Test',
        brand_name: 'Brand Name Test',
        perception: 'Brand Perception',
        pmf: 'PMF Survey',
      })[kind] ?? 'Brand Awareness';

      const { campaign } = await window.api.createCampaign({
        title: `${titlePrefix} ${brand}`,
        brandId: brandId || undefined,
        industryContext: industry,
        targetRegion: region,
        kind: kind || 'top_of_mind',
        targetResponses: reward.quota || 0,
        competitors,
        respondentFields,
      });
      // 2) save questions
      if (questions.length > 0) {
        await window.api.putQuestions(campaign.id, questions);
      }
      // 3) save reward
      await window.api.putReward(campaign.id, {
        rewardType: reward.rewardType,
        quota: reward.quota,
        valueOrLink: reward.valueOrLink,
      });
      // 4) flip to active
      await window.api.updateCampaign(campaign.id, { status: 'active' });

      setPublished({ id: campaign.id, slug: campaign.publicSlug });
      onPublished?.(campaign);
    } catch (err) {
      setError(err.message || 'Gagal mempublikasikan campaign');
    } finally {
      setPublishing(false);
    }
  };

  return (
    <div className="fade-in">
      <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>
        {published ? 'Campaign Aktif 🎉' : 'Siap Dipublikasikan'}
      </h2>
      <p style={{ margin: '0 0 20px', color: 'var(--ink-3)', fontSize: 13.5 }}>
        {published
          ? 'Sebarkan link di bawah ke pelangganmu — respons akan masuk ke dashboard.'
          : 'Cek ringkasan, lalu sebarkan link survei.'}
      </p>

      <div className="card" style={{ padding: 20, marginBottom: 12 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          {[
            ['Brand', brand],
            ['Kompetitor', `${competitors.length} brand`],
            ['Pertanyaan', `${questions.length} buah`],
            ['Hadiah', reward.valueOrLink || '—'],
          ].map(([k, v]) => (
            <div key={k}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{k}</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {published && (
        <div className="card" style={{ padding: 20, marginBottom: 12 }}>
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>Link Survei</div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', padding: 10, background: 'var(--bg-2)', borderRadius: 10, border: '1px solid var(--line)' }}>
            <I.Link size={14} style={{ color: 'var(--ink-3)' }} />
            <a href={fullUrl} target="_blank" rel="noopener" className="mono" style={{ flex: 1, fontSize: 13, color: 'var(--primary)', textDecoration: 'none', overflow: 'hidden', textOverflow: 'ellipsis' }}>{fullUrl}</a>
            <button className="btn btn-soft" onClick={copy} style={{ padding: '6px 10px' }}>
              {copied ? <><I.Check size={12} />Tersalin</> : <><I.Copy size={12} />Salin</>}
            </button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <a className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center', textDecoration: 'none', color: 'inherit' }}
               href={`https://wa.me/?text=${encodeURIComponent(fullUrl)}`} target="_blank" rel="noopener">
              WhatsApp
            </a>
            <button className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center' }} onClick={copy}>Salin Link</button>
            <a className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center', textDecoration: 'none', color: 'inherit' }}
               href={fullUrl} target="_blank" rel="noopener">Buka Survei</a>
          </div>
        </div>
      )}

      {error && (
        <div style={{ marginBottom: 12, padding: 10, borderRadius: 8, background: 'var(--danger-soft)', color: 'var(--danger)', fontSize: 12.5 }}>
          {error}
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
        <button className="btn btn-ghost" onClick={onBack} disabled={publishing}>
          <I.ChevronLeft size={14} />Kembali
        </button>
        {!published ? (
          <button className="btn btn-primary" onClick={publish} disabled={publishing} style={{ opacity: publishing ? 0.7 : 1 }}>
            <I.Send size={14} />{publishing ? 'Mempublikasikan…' : 'Publikasikan Sekarang'}
          </button>
        ) : (
          <button className="btn btn-primary" onClick={() => onPublished?.(null, 'goto-dashboard')}>
            Buka Dashboard <I.ArrowRight size={14} />
          </button>
        )}
      </div>
    </div>
  );
}

// Expose helper components ke window supaya CampaignEditor (campaign-editor.jsx)
// bisa reuse — menghindari duplikasi logika edit pertanyaan & picker wilayah.
Object.assign(window, { CampaignBuilder, QuestionEditor, QuestionRow, RegionPicker });
