// Main app shell — desktop frame with sidebar + view switcher
const { useState: useState_app } = React;

function AdminApp() {
  const [view, setView] = useState_app('dash');

  return (
    <div style={{ display: 'flex', height: '100%', overflow: 'hidden', background: 'var(--bg)' }}>
      <Sidebar active={view} onNav={setView} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {view === 'dash' && <AdminDashboard />}
        {view === 'builder' && <CampaignBuilder />}
        {view === 'landing' && <LandingCustomizer />}
        {view === 'reward' && <RewardsView />}
        {view === 'responses' && <ResponsesView />}
      </div>
    </div>
  );
}

// Light placeholder views so sidebar nav doesn't dead-end
// Default visual treatment per reward-type for custom presets (yang tidak
// punya bg/color/emoji explicit dari katalog built-in).
const REWARD_TYPE_DEFAULTS = {
  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)' },
};

// Normalize built-in & custom preset ke shape yang sama untuk render + pin.
function normalizeBuiltIn(p) {
  return {
    id: p.id,
    name: p.name,
    description: p.desc,
    rewardType: p.type,
    valueOrLink: p.valueOrLink,
    valueLabel: p.value,        // mis. "Rp 10.000" — display-only
    quota: p.quota || 0,
    emoji: p.emoji,
    bg: p.bg,
    color: p.color,
    tag: p.tag,
    custom: false,
  };
}
function normalizeCustom(p) {
  const fb = REWARD_TYPE_DEFAULTS[p.rewardType] || REWARD_TYPE_DEFAULTS.voucher;
  return {
    id: p.id,
    name: p.name,
    description: p.description,
    rewardType: p.rewardType,
    valueOrLink: p.valueOrLink,
    valueLabel: p.valueOrLink,  // untuk custom, label = value persis
    quota: p.quota || 0,
    emoji: p.emoji || fb.emoji,
    bg: fb.bg,
    color: fb.color,
    tag: 'Saya',
    custom: true,
  };
}

// Rewards screen — preset gallery + claims overview. Built-in presets dari
// templates.jsx (REWARD_PRESETS); custom presets per-workspace dari
// /api/reward-presets. Klik kartu untuk pin sebagai default campaign berikutnya.
function RewardsView() {
  const builtIn = (window.REWARD_PRESETS || []).map(normalizeBuiltIn);
  const [custom, setCustom] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [pinnedId, setPinnedId] = React.useState(() => window.__pinnedReward?.id ?? null);
  const [editing, setEditing] = React.useState(null); // 'new' | preset object | null
  const [error, setError] = React.useState(null);

  const refresh = React.useCallback(() => {
    setLoading(true);
    window.api
      .listRewardPresets()
      .then((r) => setCustom((r.presets || []).map(normalizeCustom)))
      .catch(() => setCustom([]))
      .finally(() => setLoading(false));
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const pin = (preset) => {
    window.__pinnedReward = {
      id: preset.id,
      type: preset.rewardType,
      valueOrLink: preset.valueOrLink,
      quota: preset.quota || 0,
      name: preset.name,
    };
    setPinnedId(preset.id);
  };
  const unpin = () => {
    window.__pinnedReward = null;
    setPinnedId(null);
  };

  const pinnedPreset = [...custom, ...builtIn].find((p) => p.id === pinnedId);

  const removeCustom = async (id) => {
    if (!window.confirm('Hapus hadiah ini? Campaign yang sudah pakai tidak terdampak.')) return;
    try {
      await window.api.deleteRewardPreset(id);
      if (pinnedId === id) unpin();
      await refresh();
    } catch (e) { setError(e.message); }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <TopBar title="Rewards Center" subtitle="Pilih hadiah — built-in atau bikin sendiri" />
      <div className="scroll" style={{ flex: 1, overflow: 'auto', padding: 24, background: 'var(--bg)' }}>

        {/* Hero CTA card */}
        <div className="card" style={{
          padding: 22, marginBottom: 22,
          background: 'linear-gradient(135deg, var(--primary), oklch(0.42 0.20 290))',
          color: 'white', border: 'none',
          display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 18,
        }}>
          <div>
            <div style={{ fontSize: 11, opacity: 0.85, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>
              Hadiah meningkatkan completion 3×
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em', margin: '6px 0 4px' }}>
              {pinnedPreset
                ? `Siap pakai: ${pinnedPreset.name}`
                : 'Pilih satu hadiah, langsung pakai di campaign berikutnya.'}
            </div>
            <div style={{ fontSize: 13, opacity: 0.92, lineHeight: 1.5 }}>
              {pinnedPreset
                ? 'Hadiah ini akan otomatis terisi saat kamu buat riset baru. Kamu masih bisa override per-campaign.'
                : 'Klik kartu hadiah di bawah, atau bikin custom hadiah-mu sendiri.'}
            </div>
          </div>
          {pinnedPreset && (
            <button onClick={unpin} className="btn" style={{
              background: 'rgba(255,255,255,0.18)', color: 'white', border: '1px solid rgba(255,255,255,0.28)',
            }}>Lepas pin</button>
          )}
        </div>

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

        {/* ─── Custom (Hadiah Saya) section ─────────────────────────── */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 700 }}>Hadiah Saya</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>
                Bikin hadiah custom — voucher toko sendiri, merchandise, akses eksklusif.
              </div>
            </div>
            <button className="btn btn-primary" onClick={() => { setEditing('new'); setError(null); }}>
              <I.Plus size={14} /> Tambah hadiah
            </button>
          </div>

          {editing && (
            <RewardPresetForm
              key={editing === 'new' ? 'new' : editing.id}
              initial={editing === 'new' ? null : editing}
              onCancel={() => setEditing(null)}
              onSaved={async () => { setEditing(null); await refresh(); }}
            />
          )}

          {!loading && custom.length === 0 && !editing && (
            <div style={{
              padding: 24, textAlign: 'center', borderRadius: 12,
              border: '1.5px dashed var(--line-2)', background: 'var(--surface)',
              color: 'var(--ink-3)', fontSize: 13, lineHeight: 1.55,
            }}>
              Belum ada hadiah custom. Bikin hadiah pertamamu — misalnya
              <b style={{ color: 'var(--ink-2)' }}> "Voucher Outlet Saya 20rb"</b> atau
              <b style={{ color: 'var(--ink-2)' }}> "Free coffee 1 cup"</b>.
            </div>
          )}

          {custom.length > 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
              {custom.map((p) => (
                <PresetCard
                  key={p.id}
                  preset={p}
                  pinned={pinnedId === p.id}
                  onPin={() => pin(p)}
                  onEdit={() => setEditing(p)}
                  onDelete={() => removeCustom(p.id)}
                />
              ))}
            </div>
          )}
        </div>

        {/* ─── Built-in section ────────────────────────────────────── */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 16, fontWeight: 700 }}>Hadiah Siap Pakai</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>
              {builtIn.length} preset built-in · cocok untuk pasar Indonesia
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
            {builtIn.map((p) => (
              <PresetCard
                key={p.id}
                preset={p}
                pinned={pinnedId === p.id}
                onPin={() => pin(p)}
              />
            ))}
          </div>
        </div>

        {/* Stats + claims (sample data — TODO: wire to /api per-campaign aggregate) */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 16 }}>
          <Stat label="Total Hadiah Dibagikan" value="3,408" delta={12.4} hint="bulan ini" />
          <Stat label="Klaim Rate" value="93.5" suffix="%" delta={2.1} hint="di atas rata-rata industri" />
          <Stat label="Sisa Kuota" value="799" delta={null} hint="dari 2.000 voucher Q2" />
        </div>
        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>Klaim Terbaru</div>
          <table style={{ width: '100%', fontSize: 13, borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ textAlign: 'left', color: 'var(--ink-3)', fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                <th style={{ padding: '8px 0', fontWeight: 600 }}>Responden</th>
                <th style={{ padding: '8px 0', fontWeight: 600 }}>Wilayah</th>
                <th style={{ padding: '8px 0', fontWeight: 600 }}>Hadiah</th>
                <th style={{ padding: '8px 0', fontWeight: 600 }}>Kode</th>
                <th style={{ padding: '8px 0', fontWeight: 600 }}>Status</th>
              </tr>
            </thead>
            <tbody>
              {[
                ['Rizki H.', 'Gubeng', 'Voucher 10K', 'KK-9X4M-PR2N', 'Klaim'],
                ['Maya P.', 'Sukolilo', 'Voucher 10K', 'KK-7T2L-XK4N', 'Klaim'],
                ['Anonim', 'Tegalsari', 'Voucher 10K', 'KK-2P5R-VW9K', 'Pending'],
                ['Dimas A.', 'Rungkut', 'Voucher 10K', 'KK-4M8B-NX2J', 'Klaim'],
                ['Sari W.', 'Mulyorejo', 'Voucher 10K', 'KK-6K1C-RT8X', 'Klaim'],
              ].map((r, i) => (
                <tr key={i} style={{ borderTop: '1px solid var(--line)' }}>
                  <td style={{ padding: '10px 0' }}>{r[0]}</td>
                  <td style={{ padding: '10px 0', color: 'var(--ink-2)' }}>{r[1]}</td>
                  <td style={{ padding: '10px 0' }}>{r[2]}</td>
                  <td style={{ padding: '10px 0' }}><span className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>{r[3]}</span></td>
                  <td style={{ padding: '10px 0' }}>
                    <span className={`badge ${r[4] === 'Klaim' ? 'badge-success' : ''}`}>{r[4]}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// Reusable preset card — built-in & custom render lewat sini supaya layout
// konsisten. Owner custom dapat tombol edit + delete; built-in cuma pin.
function PresetCard({ preset, pinned, onPin, onEdit, onDelete }) {
  return (
    <div className="card" style={{
      padding: 16, position: 'relative', overflow: 'hidden',
      border: pinned ? '1.5px solid var(--primary)' : '1px solid var(--line)',
      boxShadow: pinned ? '0 0 0 4px oklch(0.52 0.18 265 / 0.10)' : 'var(--shadow-sm)',
      display: 'flex', flexDirection: 'column', gap: 10,
      transition: 'all 140ms',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12,
          background: preset.bg, color: preset.color,
          display: 'grid', placeItems: 'center',
          fontSize: 24, lineHeight: 1, flexShrink: 0,
        }}>{preset.emoji}</div>
        {preset.tag && (
          <span style={{
            fontSize: 10, padding: '3px 8px', borderRadius: 999, fontWeight: 600,
            background: preset.bg, color: preset.color, letterSpacing: '0.02em',
          }}>{preset.tag}</span>
        )}
      </div>

      <div>
        <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.3 }}>{preset.name}</div>
        <div className="mono" style={{ fontSize: 13, color: preset.color, fontWeight: 700, marginTop: 4, wordBreak: 'break-word' }}>
          {preset.valueLabel}
        </div>
        {preset.description && (
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6, lineHeight: 1.5, minHeight: 36 }}>
            {preset.description}
          </div>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto', paddingTop: 8, borderTop: '1px solid var(--line)', gap: 6 }}>
        <span className="badge" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          {preset.rewardType.replace('_', ' ')}
        </span>
        <div style={{ display: 'flex', gap: 6 }}>
          {preset.custom && onEdit && (
            <button onClick={onEdit} className="btn btn-ghost" title="Edit"
              style={{ padding: 6 }}><I.Edit size={13} /></button>
          )}
          {preset.custom && onDelete && (
            <button onClick={onDelete} className="btn btn-ghost" title="Hapus"
              style={{ padding: 6, color: 'var(--danger)' }}><I.Trash size={13} /></button>
          )}
          <button
            onClick={onPin}
            className={pinned ? 'btn btn-primary' : 'btn btn-soft'}
            style={{ padding: '6px 12px', fontSize: 12 }}
          >
            {pinned ? <><I.Check size={12} /> Tersematkan</> : 'Pakai default'}
          </button>
        </div>
      </div>
    </div>
  );
}

// Inline form untuk add / edit custom reward preset.
// Disimpan via POST /api/reward-presets atau PATCH /api/reward-presets/:id.
function RewardPresetForm({ initial, onCancel, onSaved }) {
  const [name, setName] = React.useState(initial?.name ?? '');
  const [rewardType, setRewardType] = React.useState(initial?.rewardType ?? 'voucher');
  const [valueOrLink, setValueOrLink] = React.useState(initial?.valueOrLink ?? '');
  const [description, setDescription] = React.useState(initial?.description ?? '');
  const [emoji, setEmoji] = React.useState(initial?.emoji ?? '');
  const [quota, setQuota] = React.useState(initial?.quota ?? 0);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  const save = async () => {
    if (!name.trim() || !valueOrLink.trim()) return;
    setBusy(true); setError(null);
    try {
      const payload = {
        name: name.trim(),
        rewardType,
        valueOrLink: valueOrLink.trim(),
        description: description.trim() || null,
        emoji: emoji.trim() || null,
        quota: Number(quota) || 0,
      };
      if (initial?.id) {
        await window.api.updateRewardPreset(initial.id, payload);
      } else {
        await window.api.createRewardPreset(payload);
      }
      await onSaved?.();
    } catch (e) {
      setError(e.message || 'Gagal menyimpan');
    } finally { setBusy(false); }
  };

  const typeOptions = [
    { id: 'voucher',        label: 'Voucher',         hint: 'Kode unik / cetak / link redeem' },
    { id: 'e_wallet',       label: 'E-Wallet',        hint: 'Cashback ke OVO / GoPay / DANA' },
    { id: 'promo_code',     label: 'Kode Promo',      hint: 'Diskon di outlet sendiri' },
    { id: 'digital_access', label: 'Akses Digital',   hint: 'PDF / link / akses eksklusif' },
  ];

  return (
    <div className="card" style={{
      padding: 22, marginBottom: 14,
      border: '1.5px solid var(--primary)',
      boxShadow: '0 0 0 4px oklch(0.52 0.18 265 / 0.10)',
    }}>
      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>
        {initial ? `Edit ${initial.name}` : 'Tambah hadiah baru'}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 80px', gap: 10, marginBottom: 12 }}>
        <div>
          <label className="label">Nama hadiah</label>
          <input className="input" value={name} onChange={(e) => setName(e.target.value)}
            placeholder="cth. Voucher Outlet Saya 20rb" />
        </div>
        <div>
          <label className="label">Emoji</label>
          <input className="input" value={emoji} onChange={(e) => setEmoji(e.target.value)}
            placeholder="🎟️" maxLength={4} style={{ textAlign: 'center', fontSize: 18 }} />
        </div>
      </div>

      <div style={{ marginBottom: 12 }}>
        <label className="label">Tipe hadiah</label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
          {typeOptions.map((t) => (
            <label key={t.id} style={{
              display: 'flex', alignItems: 'flex-start', gap: 8,
              padding: 10, borderRadius: 8, cursor: 'pointer',
              border: rewardType === t.id ? '1.5px solid var(--primary)' : '1px solid var(--line)',
              background: rewardType === t.id ? 'var(--primary-50)' : 'var(--surface)',
            }}>
              <input type="radio" checked={rewardType === t.id} onChange={() => setRewardType(t.id)} style={{ marginTop: 3 }} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{t.label}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>{t.hint}</div>
              </div>
            </label>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 12 }}>
        <label className="label">Nilai / kode / link redeem</label>
        <input className="input" value={valueOrLink} onChange={(e) => setValueOrLink(e.target.value)}
          placeholder="cth. Voucher Rp 20.000 (kode unik), atau https://..." />
        <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 4 }}>
          Teks ini muncul di landing page survey & dikirim ke responden setelah submit.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 140px', gap: 10, marginBottom: 12 }}>
        <div>
          <label className="label">Deskripsi <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>(opsional)</span></label>
          <input className="input" value={description} onChange={(e) => setDescription(e.target.value)}
            placeholder="Konteks singkat — kapan dipakai, syarat, dll." />
        </div>
        <div>
          <label className="label">Kuota saran</label>
          <input className="input" type="number" min={0} value={quota}
            onChange={(e) => setQuota(e.target.value)} placeholder="0" />
        </div>
      </div>

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

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <button className="btn btn-ghost" onClick={onCancel} disabled={busy}>Batal</button>
        <button className="btn btn-primary" onClick={save}
          disabled={busy || !name.trim() || !valueOrLink.trim()}>
          {busy ? 'Menyimpan…' : (initial ? 'Simpan perubahan' : 'Tambah hadiah')}
        </button>
      </div>
    </div>
  );
}

// Live ResponsesView — picks user's active campaign, loads analytics + responses
// from the backend, and lets you drill into each response's individual answers.
function ResponsesView() {
  const [campaigns, setCampaigns] = React.useState([]);
  const [selectedId, setSelectedId] = React.useState(null);
  const [analytics, setAnalytics] = React.useState(null);
  const [responses, setResponses] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [opened, setOpened] = React.useState(null); // { response, answers }

  // Load campaigns once
  React.useEffect(() => {
    window.api
      .listCampaigns()
      .then((r) => {
        const list = r.campaigns || [];
        setCampaigns(list);
        // Default to first active campaign, fallback to first
        const active = list.find((c) => c.status === 'active') || list[0];
        if (active) setSelectedId(active.id);
        else setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  // Load analytics + responses whenever selectedId changes
  React.useEffect(() => {
    if (!selectedId) return;
    setLoading(true);
    Promise.all([
      window.api.analytics(selectedId),
      window.api.listResponses(selectedId, 100),
    ])
      .then(([a, r]) => {
        setAnalytics(a);
        setResponses(r.responses || []);
      })
      .catch(() => {
        setAnalytics(null);
        setResponses([]);
      })
      .finally(() => setLoading(false));
  }, [selectedId]);

  const selected = campaigns.find((c) => c.id === selectedId);
  const claimRatePct = analytics ? Math.round((analytics.claimRate || 0) * 100) : 0;

  if (campaigns.length === 0 && !loading) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <TopBar title="Hasil Riset" subtitle="Belum ada campaign yang dibuat" />
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', padding: 24 }}>
          <div className="card" style={{ padding: 32, textAlign: 'center', maxWidth: 400 }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>📋</div>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>Belum ada campaign</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 16 }}>
              Buat campaign pertamamu dari sidebar "Riset Baru". Hasilnya akan muncul di sini begitu ada respons masuk.
            </div>
          </div>
        </div>
      </div>
    );
  }

  const publicUrl = selected?.publicSlug
    ? `${window.location.origin}/survey/${selected.publicSlug}`
    : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <TopBar
        title="Hasil Riset"
        subtitle={
          selected
            ? `${(analytics?.totalResponses ?? 0).toLocaleString('id-ID')} respons untuk "${selected.title}"`
            : 'Pilih campaign untuk melihat hasilnya'
        }
        right={
          <div style={{ display: 'flex', gap: 6 }}>
            {selected && (
              <a className="btn btn-ghost" href={window.api.csvExportUrl(selected.id)}>
                <I.ArrowDown size={14} />CSV
              </a>
            )}
            {publicUrl && (
              <a className="btn btn-ghost" href={publicUrl} target="_blank" rel="noopener">
                <I.Eye size={14} />Buka Survei
              </a>
            )}
            {selected && (
              <button
                className="btn btn-ghost"
                style={{ color: 'var(--danger)' }}
                onClick={async () => {
                  if (!confirm(`Hapus campaign "${selected.title}"? Respons & jawabannya juga ikut terhapus.`)) return;
                  try {
                    await window.api.deleteCampaign(selected.id);
                    const remaining = campaigns.filter((c) => c.id !== selected.id);
                    setCampaigns(remaining);
                    setSelectedId(remaining[0]?.id ?? null);
                    setAnalytics(null);
                    setResponses([]);
                  } catch (err) {
                    alert(err.message);
                  }
                }}
              >
                <I.Trash size={14} />Hapus
              </button>
            )}
          </div>
        }
      />

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

        {/* Campaign picker */}
        <div className="card" style={{ padding: 14, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <label className="label" style={{ margin: 0, whiteSpace: 'nowrap' }}>Campaign:</label>
          <select
            className="select"
            value={selectedId || ''}
            onChange={(e) => setSelectedId(e.target.value)}
            style={{ flex: 1 }}
          >
            {campaigns.map((c) => (
              <option key={c.id} value={c.id}>
                {c.title} {c.status !== 'active' ? `(${c.status})` : ''}
              </option>
            ))}
          </select>
          {selected && (
            <span className={`badge ${selected.status === 'active' ? 'badge-success' : ''}`}>
              {selected.status}
            </span>
          )}
        </div>

        {/* Analytics summary */}
        {analytics && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 14 }}>
            <Stat
              label="Total Respons"
              value={analytics.totalResponses.toLocaleString('id-ID')}
              hint={selected?.targetResponses
                ? `dari target ${selected.targetResponses.toLocaleString('id-ID')}`
                : 'sejak campaign aktif'}
            />
            <Stat
              label="Wilayah Aktif"
              value={analytics.byRegion?.filter((r) => r.region).length ?? 0}
              hint="kecamatan / kota dengan respons"
            />
            <Stat
              label="Klaim Hadiah"
              value={claimRatePct}
              suffix="%"
              hint={`${responses.filter((r) => r.rewardClaimed).length} dari ${analytics.totalResponses} responden`}
            />
          </div>
        )}

        {/* Responses table */}
        <div className="card" style={{ padding: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ fontWeight: 600, fontSize: 14 }}>Respons Terbaru</div>
            {loading && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>memuat…</span>}
            <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)' }}>
              {responses.length} {responses.length === 100 ? '(maks 100)' : ''}
            </span>
          </div>

          {responses.length === 0 && !loading && (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13.5 }}>
              <div style={{ fontSize: 26, marginBottom: 8 }}>🌱</div>
              Belum ada respons masuk.
              {publicUrl && (
                <div style={{ marginTop: 8, fontSize: 12 }}>
                  Sebarkan link: <a href={publicUrl} target="_blank" rel="noopener" className="mono" style={{ color: 'var(--primary)' }}>{publicUrl}</a>
                </div>
              )}
            </div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {responses.map((r, i) => {
              const ts = new Date(r.submittedAt);
              const initial = (r.respondentName || 'A').slice(0, 1).toUpperCase();
              return (
                <button
                  key={r.id}
                  onClick={() => {
                    window.api
                      .request(`/api/campaigns/${selectedId}/responses/${r.id}`)
                      .then(setOpened)
                      .catch(() => {});
                  }}
                  style={{
                    display: 'grid', gridTemplateColumns: 'auto 1fr auto auto auto',
                    alignItems: 'center', gap: 14, padding: '10px 14px',
                    background: 'var(--bg-2)', borderRadius: 10, fontSize: 13,
                    border: '1px solid transparent', textAlign: 'left', cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--line-2)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'transparent'; }}
                >
                  <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--primary-50)', color: 'var(--primary)', display: 'grid', placeItems: 'center', fontWeight: 600, fontSize: 12 }}>
                    {initial}
                  </div>
                  <div>
                    <div style={{ fontWeight: 500 }}>{r.respondentName || 'Anonim'}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
                      {r.rewardCode ? <>kode <span className="mono" style={{ color: 'var(--primary)' }}>{r.rewardCode}</span></> : 'belum klaim hadiah'}
                    </div>
                  </div>
                  {r.region && (
                    <span className="badge"><I.Pin size={11} />{r.region}</span>
                  )}
                  <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
                    {ts.toLocaleString('id-ID', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                  </span>
                  <I.ChevronRight size={14} style={{ color: 'var(--ink-3)' }} />
                </button>
              );
            })}
          </div>
        </div>

        {/* By-region breakdown */}
        {analytics?.byRegion && analytics.byRegion.length > 0 && (
          <div className="card" style={{ padding: 20, marginTop: 14 }}>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>Sebaran per Wilayah</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {analytics.byRegion
                .filter((b) => b.region)
                .sort((a, b) => b.n - a.n)
                .map((b) => {
                  const pct = analytics.totalResponses > 0 ? (b.n / analytics.totalResponses) * 100 : 0;
                  return (
                    <div key={b.region} style={{ display: 'grid', gridTemplateColumns: '180px 1fr auto', gap: 10, alignItems: 'center', fontSize: 13 }}>
                      <span>{b.region}</span>
                      <div className="progress"><span style={{ width: pct + '%' }} /></div>
                      <span className="mono" style={{ fontSize: 12, color: 'var(--ink-2)', minWidth: 60, textAlign: 'right' }}>
                        {b.n} <span style={{ color: 'var(--ink-3)' }}>· {pct.toFixed(0)}%</span>
                      </span>
                    </div>
                  );
                })}
            </div>
          </div>
        )}
      </div>

      {/* Detail drawer */}
      {opened && (
        <ResponseDetail data={opened} onClose={() => setOpened(null)} />
      )}
    </div>
  );
}

function ResponseDetail({ data, onClose }) {
  const r = data.response;
  const ts = new Date(r.submittedAt);
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, background: 'rgba(15,18,30,0.5)',
        display: 'grid', placeItems: 'center', zIndex: 50, padding: 24,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="card"
        style={{ width: '100%', maxWidth: 560, maxHeight: '85vh', display: 'flex', flexDirection: 'column' }}
      >
        <div style={{ padding: 18, borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15 }}>
              {r.respondentName || 'Anonim'}
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
              {ts.toLocaleString('id-ID', { dateStyle: 'medium', timeStyle: 'short' })}
              {r.region && ` · ${r.region}`}
              {r.latitude && r.longitude && (
                <span className="mono"> · {r.latitude.toFixed(3)}, {r.longitude.toFixed(3)}</span>
              )}
            </div>
            {r.rewardCode && (
              <div style={{ fontSize: 12, marginTop: 6 }}>
                Kode hadiah: <span className="mono" style={{ color: 'var(--primary)', fontWeight: 600 }}>{r.rewardCode}</span>
              </div>
            )}
          </div>
          <button onClick={onClose} className="btn btn-ghost" style={{ marginLeft: 'auto', padding: 6 }}>
            <I.X size={14} />
          </button>
        </div>

        <div className="scroll" style={{ flex: 1, overflow: 'auto', padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {data.answers.length === 0 && (
            <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>Tidak ada jawaban tercatat.</div>
          )}
          {data.answers.map((a) => (
            <div key={a.id}>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>
                {a.questionType}
              </div>
              <div style={{ fontSize: 13.5, fontWeight: 500, marginTop: 2 }}>{a.questionText}</div>
              <div style={{ fontSize: 13.5, color: 'var(--ink-2)', background: 'var(--bg-2)', padding: '8px 10px', borderRadius: 8, marginTop: 6 }}>
                {a.answerText || <em style={{ color: 'var(--ink-3)' }}>(kosong)</em>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminApp, RewardsView, ResponsesView });
