// report.jsx — "Buat Laporan" stepper, submit asli ke Supabase. Exported to window.

const STEPS = ['Kategori', 'Detail', 'Lokasi', 'Kirim'];

function StepDots({ step }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1 }}>
      {STEPS.map((s, i) => (
        <div key={s} style={{ flex: 1, height: 4, borderRadius: 4,
          background: i <= step ? 'var(--primary)' : 'var(--border-strong)',
          transition: 'background var(--dur) var(--ease)' }} />
      ))}
    </div>
  );
}

function ReportFlow({ initialCat, clusters = [], onClose, onDone }) {
  const [step, setStep] = React.useState(0);
  const [cat, setCat] = React.useState(initialCat && CATS[initialCat] ? initialCat : null);
  const [title, setTitle] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [ig, setIg] = React.useState('');
  const [address, setAddress] = React.useState('');
  const [clusterId, setClusterId] = React.useState('');
  const [anon, setAnon] = React.useState(false);
  const [photoFile, setPhotoFile] = React.useState(null);
  const [photoPrev, setPhotoPrev] = React.useState(null);
  const [loc, setLoc] = React.useState({ lat: -6.2436, lng: 106.6285, got: false });
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const fileRef = React.useRef(null);
  const c = cat ? CATS[cat] : null;
  const dark = false;

  React.useEffect(() => {
    if (step === 2 && !loc.got && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        p => setLoc({ lat: p.coords.latitude, lng: p.coords.longitude, got: true }),
        () => setLoc(l => ({ ...l, got: true })),
        { enableHighAccuracy: true, timeout: 8000 }
      );
    }
  }, [step]);

  const onPickFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    setPhotoFile(f);
    if (photoPrev) URL.revokeObjectURL(photoPrev);
    setPhotoPrev(URL.createObjectURL(f));
  };

  const doSubmit = async () => {
    setBusy(true); setErr('');
    const res = await gsData.submitReport({
      cat, title: title.trim(), desc, anon, lat: loc.lat, lng: loc.lng,
      address: address.trim() || null, cluster_id: clusterId || null,
      photoFile, instagram_url: ig.trim() || null,
    });
    setBusy(false);
    if (res.error) { setErr('Gagal mengirim: ' + res.error); return; }
    setSent(true); setTimeout(onDone, 1600);
  };

  const next = () => {
    if (step === 0 && !cat) return setErr('Pilih kategori dulu ya');
    if (step === 1 && !title.trim()) return setErr('Judul singkat diperlukan ya');
    setErr('');
    if (step === 3) return doSubmit();
    setStep(s => Math.min(3, s + 1));
  };
  const back = () => { setErr(''); step === 0 ? onClose() : setStep(s => s - 1); };

  if (sent) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        background: 'var(--surface)', padding: 32, textAlign: 'center', animation: 'gsFade 200ms var(--ease)' }}>
        <div style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--lime-50)', display: 'grid', placeItems: 'center', marginBottom: 22 }}>
          <span style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--lime)', display: 'grid', placeItems: 'center' }}>
            <Icon name="check" size={34} color="#fff" sw={2.6} />
          </span>
        </div>
        <h2 style={{ fontSize: 22, fontWeight: 800, color: 'var(--text-1)', marginBottom: 8 }}>Laporan terkirim!</h2>
        <p style={{ fontSize: 14.5, color: 'var(--text-2)', maxWidth: 270 }}>Terima kasih sudah menjaga lingkungan kita. Kamu dapat <b>+50 poin</b>. Warga & pengurus akan segera melihat laporanmu.</p>
      </div>
    );
  }

  const selCluster = clusters.find(c => c.id === clusterId);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--surface)' }}>
      <div style={{ paddingTop: SAFE_TOP, background: 'var(--surface)', borderBottom: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 16px 14px' }}>
          <button onClick={back} style={{ width: 36, height: 36, borderRadius: '50%', border: '1px solid var(--border)',
            background: 'var(--surface)', display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0 }}>
            <Icon name={step === 0 ? 'x' : 'chevL'} size={18} color="var(--text-2)" />
          </button>
          <StepDots step={step} />
          <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-3)', width: 30, textAlign: 'right' }}>{step + 1}/4</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '22px 20px 16px', scrollbarWidth: 'none' }}>
        <h2 style={{ fontSize: 21, fontWeight: 800, color: 'var(--text-1)', marginBottom: 5, letterSpacing: '-0.02em' }}>
          {['Apa yang terjadi?', 'Ceritakan detailnya', 'Di mana lokasinya?', 'Periksa & kirim'][step]}
        </h2>
        <p style={{ fontSize: 13.5, color: 'var(--text-2)', marginBottom: 22 }}>
          {['Pilih kategori laporanmu', 'Tambahkan foto dan deskripsi singkat', 'Pastikan titik lokasi sudah benar', 'Pastikan semua sudah benar'][step]}
        </p>

        {step === 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 11 }}>
            {CAT_ORDER.map(k => {
              const cc = CATS[k]; const on = cat === k;
              return (
                <button key={k} onClick={() => { setCat(k); setErr(''); }}
                  style={{ position: 'relative', padding: '18px 14px', borderRadius: 'var(--r-card)', cursor: 'pointer', textAlign: 'left',
                    border: `2px solid ${on ? cc.color : 'var(--border)'}`, background: on ? cc.soft : 'var(--surface)',
                    transform: on ? 'scale(1.015)' : 'scale(1)', transition: 'all var(--dur) var(--ease)', fontFamily: 'var(--font)' }}>
                  <span style={{ display: 'inline-flex', width: 44, height: 44, borderRadius: '50%', background: cc.color,
                    alignItems: 'center', justifyContent: 'center', marginBottom: 11 }}>
                    <Icon name={cc.icon} size={23} color="#fff" sw={2.2} />
                  </span>
                  <span style={{ display: 'block', fontSize: 14.5, fontWeight: 800, color: 'var(--text-1)' }}>{cc.label}</span>
                  {on && <span style={{ position: 'absolute', top: 12, right: 12, width: 22, height: 22, borderRadius: '50%',
                    background: cc.color, display: 'grid', placeItems: 'center' }}><Icon name="check" size={13} color="#fff" sw={3} /></span>}
                </button>
              );
            })}
          </div>
        )}

        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <input ref={fileRef} type="file" accept="image/*" capture="environment" onChange={onPickFile} style={{ display: 'none' }} />
            <button onClick={() => fileRef.current && fileRef.current.click()}
              style={{ position: 'relative', display: 'block', width: '100%', height: 168, borderRadius: 14, overflow: 'hidden', cursor: 'pointer',
                border: photoPrev ? 'none' : '2px dashed var(--border-strong)', background: c ? c.soft : 'var(--surface-2)', padding: 0 }}>
              {photoPrev ? (
                <img src={photoPrev} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              ) : (
                <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 8, color: 'var(--text-2)' }}>
                  <Icon name="camera" size={30} color={c ? c.color : 'var(--text-3)'} />
                  <span style={{ fontSize: 13, fontWeight: 600 }}>Tap untuk foto atau pilih dari galeri</span>
                </span>
              )}
            </button>
            <div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>Judul singkat</label>
              <input value={title} onChange={e => { setTitle(e.target.value); setErr(''); }} placeholder="cth. Lubang besar di Boulevard"
                style={{ width: '100%', padding: '13px 14px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)',
                  background: 'var(--surface-2)', fontFamily: 'var(--font)', fontSize: 14.5, fontWeight: 500, color: 'var(--text-1)', outline: 'none' }} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>Deskripsi <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></label>
              <div style={{ position: 'relative' }}>
                <textarea value={desc} maxLength={280} onChange={e => setDesc(e.target.value)} placeholder="Ceritakan apa yang terjadi..."
                  rows={3} style={{ width: '100%', padding: '13px 14px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)',
                    background: 'var(--surface-2)', fontFamily: 'var(--font)', fontSize: 14.5, color: 'var(--text-1)', outline: 'none', resize: 'none', lineHeight: 1.5 }} />
                <span className="mono" style={{ position: 'absolute', right: 12, bottom: 10, fontSize: 11, color: 'var(--text-3)' }}>{desc.length}/280</span>
              </div>
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>Link Instagram <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></label>
              <input value={ig} onChange={e => setIg(e.target.value)} placeholder="Tempel link story/reel warga"
                style={{ width: '100%', padding: '13px 14px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)',
                  background: 'var(--surface-2)', fontFamily: 'var(--font)', fontSize: 14, fontWeight: 500, color: 'var(--text-1)', outline: 'none' }} />
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ position: 'relative', height: 230, borderRadius: 'var(--r-card)', overflow: 'hidden', border: '1px solid var(--border)' }}>
              <GsMap reports={[]} dark={dark} showUser />
              <span style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-100%)', zIndex: 20, pointerEvents: 'none' }}>
                <span style={{ display: 'block', width: 34, height: 34, borderRadius: '40% 40% 40% 0', background: c ? c.color : 'var(--primary)',
                  transform: 'rotate(-45deg)', border: '2px solid #fff', boxShadow: '0 6px 14px rgba(15,23,42,0.4)' }} />
              </span>
              <FrostBar dark={dark} style={{ position: 'absolute', left: 12, right: 12, bottom: 12, padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 8, borderRadius: 'var(--r-chip)' }}>
                <Icon name="locate" size={15} color="var(--primary)" />
                <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-2)' }}>{loc.got ? 'Lokasi terdeteksi' : 'Mendeteksi lokasi...'}</span>
                <span className="mono" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-3)' }}>{loc.lat.toFixed(4)}, {loc.lng.toFixed(4)}</span>
              </FrostBar>
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>Nama lokasi / patokan <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></label>
              <input value={address} onChange={e => setAddress(e.target.value)} placeholder="cth. Boulevard Gading Serpong"
                style={{ width: '100%', padding: '13px 14px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)',
                  background: 'var(--surface-2)', fontFamily: 'var(--font)', fontSize: 14, fontWeight: 500, color: 'var(--text-1)', outline: 'none' }} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--text-2)', marginBottom: 7 }}>Cluster <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></label>
              <select value={clusterId} onChange={e => setClusterId(e.target.value)}
                style={{ width: '100%', padding: '13px 14px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)', background: 'var(--surface-2)',
                  fontFamily: 'var(--font)', fontSize: 14, fontWeight: 500, color: clusterId ? 'var(--text-1)' : 'var(--text-3)', outline: 'none', appearance: 'none' }}>
                <option value="">Pilih cluster (jika ada)</option>
                {clusters.map(cl => <option key={cl.id} value={cl.id}>{cl.name}</option>)}
              </select>
            </div>
          </div>
        )}

        {step === 3 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-card)', overflow: 'hidden' }}>
              {photoPrev && <img src={photoPrev} alt="" style={{ width: '100%', height: 150, objectFit: 'cover', display: 'block' }} />}
              {c && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: 14, borderBottom: '1px solid var(--border)' }}>
                  <CatSeal cat={cat} size={40} />
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: c.color }}>{c.label}</div>
                    <div style={{ fontSize: 15, fontWeight: 800, color: 'var(--text-1)' }}>{title || 'Tanpa judul'}</div>
                  </div>
                </div>
              )}
              {desc && <div style={{ padding: 14, fontSize: 13.5, color: 'var(--text-2)', lineHeight: 1.5, borderBottom: '1px solid var(--border)' }}>{desc}</div>}
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 14 }}>
                <Icon name="pin" size={16} color="var(--text-3)" />
                <span style={{ fontSize: 13, color: 'var(--text-2)', fontWeight: 600 }}>{address || 'Gading Serpong'}{selCluster ? ' · ' + selCluster.name : ''}</span>
              </div>
            </div>
            <button onClick={() => setAnon(a => !a)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '14px 16px', borderRadius: 'var(--r-md)', border: '1px solid var(--border)', background: 'var(--surface)', cursor: 'pointer', fontFamily: 'var(--font)' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="user" size={18} color="var(--text-2)" />
                <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-1)' }}>Sembunyikan nama saya</span>
              </span>
              <span style={{ width: 46, height: 28, borderRadius: 999, background: anon ? 'var(--primary)' : 'var(--border-strong)', position: 'relative', transition: 'background var(--dur) var(--ease)' }}>
                <span style={{ position: 'absolute', top: 3, left: anon ? 21 : 3, width: 22, height: 22, borderRadius: '50%', background: '#fff', transition: 'left var(--dur) var(--ease)', boxShadow: '0 1px 3px rgba(0,0,0,0.3)' }} />
              </span>
            </button>
          </div>
        )}

        {err && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16, padding: '11px 14px', borderRadius: 'var(--r-md)',
            background: 'var(--coral-50)', color: 'var(--coral-700)', fontSize: 13, fontWeight: 600 }}>
            <Icon name="shield" size={16} color="var(--coral-700)" /> {err}
          </div>
        )}
      </div>

      <div style={{ padding: '14px 20px', paddingBottom: 'max(22px, env(safe-area-inset-bottom))', borderTop: '1px solid var(--border)', background: 'var(--surface)' }}>
        <button onClick={next} disabled={busy} style={{ width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          padding: '15px', borderRadius: 'var(--r-chip)', border: 'none', cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.7 : 1,
          background: step === 3 ? 'var(--cta)' : 'var(--primary)', color: '#fff', fontFamily: 'var(--font)', fontWeight: 800, fontSize: 15,
          boxShadow: step === 3 ? 'var(--sh-cta)' : 'none' }}>
          {busy ? 'Mengirim...' : (step === 3 ? 'Kirim Laporan' : 'Lanjut')} {!busy && <Icon name="arrow" size={18} color="#fff" sw={2.4} />}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ReportFlow, STEPS });
