// lostfound.jsx — Kehilangan & Temuan. Browse + detail + lapor. Global.

const LF_CATS = [
  { key: 'barang', label: 'Barang', icon: 'tag', color: '#7C3AED' },
  { key: 'hewan', label: 'Hewan', icon: 'paw', color: '#F59E0B' },
  { key: 'dokumen', label: 'Dokumen', icon: 'doc', color: '#1B4FD8' },
  { key: 'kendaraan', label: 'Kendaraan', icon: 'car', color: '#14B8A6' },
  { key: 'lainnya', label: 'Lainnya', icon: 'grid', color: '#64748B' },
];
const LF_CAT = LF_CATS.reduce((a, c) => (a[c.key] = c, a), {});
function lfKindMeta(kind) {
  return kind === 'temuan'
    ? { label: 'TEMUAN', bg: 'var(--lime-50)', fg: 'var(--lime-700)', dot: 'var(--lime)' }
    : { label: 'HILANG', bg: 'var(--coral-50)', fg: 'var(--coral-700)', dot: 'var(--coral)' };
}
function lfTime(iso) {
  const d = new Date(iso), now = new Date(), diff = (now - d) / 1000;
  if (diff < 3600) return Math.max(1, Math.floor(diff / 60)) + ' mnt lalu';
  if (diff < 86400) return Math.floor(diff / 3600) + ' jam lalu';
  if (diff < 604800) return Math.floor(diff / 86400) + ' hari lalu';
  return d.getDate() + ' ' + ID_MON[d.getMonth()];
}

function LFCard({ item, onOpen }) {
  const cc = LF_CAT[item.category] || LF_CAT.lainnya;
  const km = lfKindMeta(item.kind);
  const resolved = item.status === 'resolved';
  return (
    <button onClick={() => onOpen(item)} style={{ display: 'flex', width: '100%', textAlign: 'left', gap: 0, padding: 0, border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)', overflow: 'hidden', background: 'var(--surface)', cursor: 'pointer', boxShadow: 'var(--sh-1)', fontFamily: 'var(--font)', opacity: resolved ? 0.62 : 1 }}>
      <div style={{ width: 84, flexShrink: 0, background: cc.color + '14', display: 'grid', placeItems: 'center', overflow: 'hidden' }}>
        {item.photo_url ? <img src={item.photo_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <Icon name={cc.icon} size={30} color={cc.color} />}
      </div>
      <div style={{ flex: 1, padding: '12px 14px', minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
          <span style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '0.04em', padding: '2px 7px', borderRadius: 999, background: km.bg, color: km.fg }}>{km.label}</span>
          <span style={{ fontSize: 11, fontWeight: 700, color: cc.color }}>{cc.label}</span>
          {resolved && <span style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 700, color: 'var(--text-3)' }}>SELESAI</span>}
        </div>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text-1)', lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{item.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--text-3)', marginTop: 5 }}>
          {item.location_text && <><Icon name="pin" size={12} color="var(--text-3)" /><span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 130 }}>{item.location_text}</span><span>·</span></>}
          <span>{lfTime(item.created_at)}</span>
        </div>
      </div>
    </button>
  );
}

function LostFoundScreen({ authed, onRequireAuth, profile, clusters = [], onCreate }) {
  const [items, setItems] = React.useState([]);
  const [kind, setKind] = React.useState('all');
  const [cat, setCat] = React.useState('all');
  const [loading, setLoading] = React.useState(true);
  const [detail, setDetail] = React.useState(null);

  const load = React.useCallback(() => {
    setLoading(true);
    gsData.loadLostFound({ kind: kind, category: cat }).then(d => { setItems(d); setLoading(false); });
  }, [kind, cat]);
  React.useEffect(() => { load(); }, [load]);
  const isOwner = detail && profile && detail.user_id === profile.id;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ paddingTop: SAFE_TOP, background: 'var(--surface)', borderBottom: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 20px 12px' }}>
          <h2 style={{ fontSize: 23, fontWeight: 800, letterSpacing: '-0.03em', color: 'var(--text-1)' }}>Kehilangan & Temuan</h2>
          <button onClick={onCreate} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '9px 14px', borderRadius: 'var(--r-chip)', border: 'none',
            background: 'var(--cta)', color: '#fff', fontWeight: 800, fontSize: 13, cursor: 'pointer', boxShadow: 'var(--sh-cta)', fontFamily: 'var(--font)' }}>
            <Icon name="plus" size={16} color="#fff" sw={2.6} /> Lapor
          </button>
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '0 20px 10px' }}>
          {[['all', 'Semua'], ['hilang', 'Hilang'], ['temuan', 'Temuan']].map(([k, l]) => (
            <button key={k} onClick={() => setKind(k)} style={{ flex: 1, padding: '9px', borderRadius: 'var(--r-chip)', cursor: 'pointer', fontFamily: 'var(--font)', fontWeight: 700, fontSize: 13,
              border: '1px solid ' + (kind === k ? 'var(--primary)' : 'var(--border)'), background: kind === k ? 'var(--primary-soft)' : 'var(--surface)', color: kind === k ? 'var(--primary)' : 'var(--text-2)' }}>{l}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '0 20px 12px', scrollbarWidth: 'none' }}>
          <Pill active={cat === 'all'} onClick={() => setCat('all')}>Semua jenis</Pill>
          {LF_CATS.map(c => <Pill key={c.key} active={cat === c.key} color={c.color} onClick={() => setCat(c.key)}>{c.label}</Pill>)}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 90px', scrollbarWidth: 'none' }}>
        {loading ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>{[0, 1, 2].map(i => <div key={i} style={{ height: 96, borderRadius: 'var(--r-card)', background: 'var(--surface-2)' }} />)}</div>
        ) : items.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 24px', color: 'var(--text-3)' }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--surface-2)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}><Icon name="search" size={28} color="var(--text-3)" /></div>
            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-2)' }}>Belum ada laporan</div>
            <div style={{ fontSize: 13, marginTop: 4 }}>Kehilangan sesuatu? Atau menemukan barang? Laporkan di sini.</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>{items.map(it => <LFCard key={it.id} item={it} onOpen={setDetail} />)}</div>
        )}
      </div>

      {detail && <LFDetailSheet item={detail} isOwner={isOwner} authed={authed} clusters={clusters} onRequireAuth={onRequireAuth} onClose={() => setDetail(null)} onChanged={() => { setDetail(null); load(); }} />}
    </div>
  );
}

function LFDetailSheet({ item, isOwner, authed, clusters = [], onRequireAuth, onClose, onChanged }) {
  const cc = LF_CAT[item.category] || LF_CAT.lainnya;
  const km = lfKindMeta(item.kind);
  const [busy, setBusy] = React.useState(false);
  const [editing, setEditing] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);

  if (editing) return <div style={{ position: 'absolute', inset: 0, zIndex: 90 }}><LostFoundEditFlow item={item} clusters={clusters} onClose={() => setEditing(false)} onDone={() => { setEditing(false); onChanged(); }} /></div>;
  const wa = item.contact_wa ? waLink(item.contact_wa, 'Halo, soal ' + (item.kind === 'temuan' ? 'barang temuan' : 'kehilangan') + ' "' + item.title + '" di gs.town.') : null;
  const mapUrl = item.lat != null && item.lng != null ? 'https://www.google.com/maps/search/?api=1&query=' + item.lat + ',' + item.lng
    : (item.location_text ? 'https://www.google.com/maps/search/?api=1&query=' + encodeURIComponent(item.location_text + ' Gading Serpong') : null);
  const act = async (fn) => { setBusy(true); await fn(); setBusy(false); onChanged(); };

  return (
    <Sheet onClose={onClose} height="90%">
      <div style={{ flex: 1, overflowY: 'auto', scrollbarWidth: 'none' }}>
        <div style={{ position: 'relative', height: item.photo_url ? 220 : 120, background: cc.color + '14', display: 'grid', placeItems: 'center', overflow: 'hidden' }}>
          {item.photo_url ? <img src={item.photo_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <Icon name={cc.icon} size={52} color={cc.color} />}
          <button onClick={onClose} style={{ position: 'absolute', top: 12, right: 12, width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.92)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="x" size={18} color="var(--s-900)" /></button>
          <span style={{ position: 'absolute', left: 16, bottom: 14, fontSize: 11, fontWeight: 800, letterSpacing: '0.05em', padding: '5px 12px', borderRadius: 999, background: km.dot, color: '#fff' }}>{km.label}</span>
        </div>
        <div style={{ padding: '18px 20px 8px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 999, background: cc.color + '18', marginBottom: 10 }}>
            <Icon name={cc.icon} size={13} color={cc.color} /><span style={{ fontSize: 11.5, fontWeight: 800, color: cc.color }}>{cc.label}</span>
            {item.status === 'resolved' && <span style={{ fontSize: 10.5, fontWeight: 800, color: 'var(--lime-700)', marginLeft: 4 }}>· SELESAI</span>}
          </div>
          <h2 style={{ fontSize: 21, fontWeight: 800, color: 'var(--text-1)', letterSpacing: '-0.02em', lineHeight: 1.3 }}>{item.title}</h2>
          {item.body && <p style={{ fontSize: 14.5, color: 'var(--text-2)', lineHeight: 1.6, whiteSpace: 'pre-wrap', margin: '12px 0' }}>{item.body}</p>}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1, marginTop: 8 }}>
            {item.location_text && (
              <button onClick={() => mapUrl && window.open(mapUrl, '_blank')} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)', border: 'none', borderBottom: '1px solid var(--border)', background: 'none', cursor: mapUrl ? 'pointer' : 'default', textAlign: 'left', width: '100%', fontFamily: 'var(--font)' }}>
                <Icon name="pin" size={18} color="var(--primary)" />
                <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-1)' }}>{item.location_text}</div>{mapUrl && <div style={{ fontSize: 12, color: 'var(--primary)', fontWeight: 600 }}>Buka di peta</div>}</div>
              </button>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0' }}>
              <Icon name="user" size={18} color="var(--primary)" />
              <div><div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-1)' }}>{item.reporter}</div><div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>Pelapor · {lfTime(item.created_at)}{item.cluster ? ' · ' + item.cluster : ''}</div></div>
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '12px 20px', paddingBottom: 26, borderTop: '1px solid var(--border)', background: 'var(--surface)' }}>
        {isOwner ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            <div style={{ display: 'flex', gap: 9 }}>
              <button disabled={busy} onClick={() => setEditing(true)} className="gs-press" style={{ flex: 1, padding: '14px', borderRadius: 'var(--r-chip)', border: 'none', background: 'var(--primary)', color: '#fff', fontWeight: 800, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--font)' }}>Edit</button>
              {item.status !== 'resolved' && <button disabled={busy} onClick={() => act(() => gsData.setLostFoundStatus(item.id, 'resolved'))} className="gs-press" style={{ flex: 1, padding: '14px', borderRadius: 'var(--r-chip)', border: '1px solid var(--border)', background: 'var(--surface)', color: 'var(--lime-700)', fontWeight: 700, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--font)' }}>Sudah ketemu</button>}
            </div>
            <button disabled={busy} onClick={() => setConfirmDel(true)} className="gs-press" style={{ width: '100%', padding: '14px', borderRadius: 'var(--r-chip)', border: 'none', background: 'var(--coral-50)', color: 'var(--coral-700)', fontWeight: 700, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--font)' }}>Hapus laporan</button>
            {confirmDel && <ConfirmDialog title="Hapus laporan?" message="Laporan kehilangan/temuan ini akan dihapus permanen." busy={busy} onCancel={() => setConfirmDel(false)} onConfirm={() => { setConfirmDel(false); act(() => gsData.deleteLostFound(item.id)); }} />}
          </div>
        ) : !item.contact_wa ? <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-3)', padding: 12 }}>Pelapor tidak mencantumkan kontak.</div>
        : !authed ? (
          <button onClick={() => onRequireAuth && onRequireAuth()} style={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', gap: 9, padding: '15px', borderRadius: 'var(--r-chip)', border: 'none', background: 'var(--cta)', color: '#fff', fontWeight: 800, fontSize: 15, cursor: 'pointer', boxShadow: 'var(--sh-cta)', fontFamily: 'var(--font)' }}>
            <Icon name="shield" size={18} color="#fff" /> Masuk untuk lihat kontak
          </button>
        ) : (
          <a href={wa} target="_blank" rel="noopener noreferrer" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, padding: '15px', borderRadius: 'var(--r-chip)', background: 'var(--cta)', color: '#fff', fontWeight: 800, fontSize: 15.5, textDecoration: 'none', boxShadow: 'var(--sh-cta)' }}>
            <Icon name="phone" size={19} color="#fff" /> Hubungi pelapor
          </a>
        )}
      </div>
    </Sheet>
  );
}

function LostFoundFlow({ clusters, profile, onClose, onDone }) {
  const [kind, setKind] = React.useState('hilang');
  const [cat, setCat] = React.useState('barang');
  const [title, setTitle] = React.useState('');
  const [body, setBody] = React.useState('');
  const [loc, setLoc] = React.useState('');
  const [clusterId, setClusterId] = React.useState('');
  const [wa, setWa] = React.useState('');
  const [photoFile, setPhotoFile] = React.useState(null);
  const [photoPrev, setPhotoPrev] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const fileRef = React.useRef(null);

  const onFile = (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 submit = async () => {
    if (!title.trim()) return setErr('Judul wajib diisi');
    setBusy(true); setErr('');
    const res = await gsData.submitLostFound({ kind, category: cat, title, body, location_text: loc, cluster_id: clusterId || null, contact_wa: wa, photoFile });
    setBusy(false);
    if (res.error) return setErr('Gagal: ' + res.error);
    setDone(true); setTimeout(onDone, 1400);
  };

  if (done) return (
    <FlowShell onClose={onClose} title="">
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 32 }}>
        <div style={{ width: 80, height: 80, borderRadius: '50%', background: 'var(--lime-50)', display: 'grid', placeItems: 'center', marginBottom: 20 }}><span style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--lime)', display: 'grid', placeItems: 'center' }}><Icon name="check" size={32} color="#fff" sw={2.6} /></span></div>
        <h2 style={{ fontSize: 21, fontWeight: 800, color: 'var(--text-1)' }}>Laporan terkirim!</h2>
        <p style={{ fontSize: 14, color: 'var(--text-2)', marginTop: 6, maxWidth: 260 }}>Semoga cepat ketemu. Warga lain bisa membantu sekarang.</p>
      </div>
    </FlowShell>
  );

  const fld = { 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' };

  return (
    <FlowShell onClose={onClose} title="Lapor Kehilangan / Temuan"
      footer={<button onClick={submit} disabled={busy} style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: 15, borderRadius: 'var(--r-chip)', border: 'none', background: 'var(--cta)', color: '#fff', fontWeight: 800, fontSize: 15, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.7 : 1, boxShadow: 'var(--sh-cta)' }}>{busy ? 'Mengirim...' : 'Kirim Laporan'}{!busy && <Icon name="arrow" size={18} color="#fff" sw={2.4} />}</button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <Lbl>Jenis laporan</Lbl>
          <div style={{ display: 'flex', gap: 9 }}>
            {[['hilang', 'Kehilangan', 'var(--coral)'], ['temuan', 'Menemukan', 'var(--lime)']].map(([k, l, col]) => (
              <button key={k} onClick={() => setKind(k)} style={{ flex: 1, padding: '13px', borderRadius: 'var(--r-md)', cursor: 'pointer', fontFamily: 'var(--font)', fontWeight: 700, fontSize: 14,
                border: '2px solid ' + (kind === k ? col : 'var(--border)'), background: kind === k ? col + '14' : 'var(--surface)', color: kind === k ? col : 'var(--text-2)' }}>{l}</button>
            ))}
          </div>
        </div>
        <div>
          <Lbl>Jenis barang</Lbl>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {LF_CATS.map(c => { const on = cat === c.key; return (
              <button key={c.key} onClick={() => setCat(c.key)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, padding: '11px 6px', borderRadius: 'var(--r-md)', cursor: 'pointer', border: '2px solid ' + (on ? c.color : 'var(--border)'), background: on ? c.color + '12' : 'var(--surface)', fontFamily: 'var(--font)' }}>
                <Icon name={c.icon} size={20} color={c.color} /><span style={{ fontSize: 10.5, fontWeight: 700, color: on ? c.color : 'var(--text-2)' }}>{c.label}</span>
              </button>); })}
          </div>
        </div>
        <div>
          <Lbl>Foto <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(sangat membantu)</span></Lbl>
          <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
          <button onClick={() => fileRef.current && fileRef.current.click()} style={{ width: '100%', height: photoPrev ? 160 : 92, borderRadius: 'var(--r-md)', border: photoPrev ? 'none' : '2px dashed var(--border-strong)', background: 'var(--surface-2)', display: 'grid', placeItems: 'center', cursor: 'pointer', overflow: 'hidden', padding: 0 }}>
            {photoPrev ? <img src={photoPrev} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: 'var(--text-3)' }}><Icon name="camera" size={24} color="var(--text-3)" /><span style={{ fontSize: 12.5, fontWeight: 600 }}>Tambah foto</span></span>}
          </button>
        </div>
        <div><Lbl>Judul</Lbl><Inp value={title} onChange={e => { setTitle(e.target.value); setErr(''); }} placeholder={kind === 'temuan' ? 'cth. Menemukan kucing oren di Allevare' : 'cth. Kehilangan dompet kulit coklat'} /></div>
        <div><Lbl>Deskripsi <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></Lbl><textarea value={body} maxLength={600} onChange={e => setBody(e.target.value)} rows={3} placeholder="Ciri-ciri, waktu, detail lain..." style={{ ...fld, resize: 'none', lineHeight: 1.5 }} /></div>
        <div><Lbl>Lokasi terakhir</Lbl><Inp value={loc} onChange={e => setLoc(e.target.value)} placeholder="cth. Sekitar Pasar Modern BSD" /></div>
        <div><Lbl>Cluster <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></Lbl>
          <select value={clusterId} onChange={e => setClusterId(e.target.value)} style={{ ...fld, appearance: 'none' }}><option value="">Pilih cluster</option>{clusters.map(cl => <option key={cl.id} value={cl.id}>{cl.name}</option>)}</select></div>
        <div><Lbl>Kontak WhatsApp</Lbl><Inp value={wa} onChange={e => setWa(e.target.value)} placeholder="08xxxxxxxxxx" type="tel" /></div>
        {err && <div style={{ display: 'flex', alignItems: 'center', gap: 8, 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>
    </FlowShell>
  );
}

function LostFoundEditFlow({ item, clusters = [], onClose, onDone }) {
  const [kind, setKind] = React.useState(item.kind || 'hilang');
  const [cat, setCat] = React.useState(item.category || 'barang');
  const [title, setTitle] = React.useState(item.title || '');
  const [body, setBody] = React.useState(item.body || '');
  const [loc, setLoc] = React.useState(item.location_text || '');
  const [clusterId, setClusterId] = React.useState(item.cluster_id || '');
  const [wa, setWa] = React.useState(item.contact_wa || '');
  const [photoFile, setPhotoFile] = React.useState(null);
  const [photoPrev, setPhotoPrev] = React.useState(item.photo_url || null);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);

  const onFile = (e) => { const f = e.target.files && e.target.files[0]; if (!f) return; setPhotoFile(f); setPhotoPrev(URL.createObjectURL(f)); };
  const submit = async () => {
    if (!title.trim()) return setErr('Judul wajib diisi');
    setBusy(true); setErr('');
    const res = await gsData.updateLostFound(item.id, { kind, category: cat, title, body, location_text: loc, cluster_id: clusterId || null, contact_wa: wa, photoFile });
    setBusy(false);
    if (res.error) return setErr('Gagal: ' + res.error);
    onDone();
  };
  const fld = { 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' };

  return (
    <FlowShell onClose={onClose} title="Edit Laporan"
      footer={<button onClick={submit} disabled={busy} className="gs-press" style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: 15, borderRadius: 'var(--r-chip)', border: 'none', background: 'var(--primary)', color: '#fff', fontWeight: 800, fontSize: 15, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.7 : 1 }}>{busy ? 'Menyimpan...' : 'Simpan perubahan'}{!busy && <Icon name="check" size={18} color="#fff" sw={2.6} />}</button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <Lbl>Jenis laporan</Lbl>
          <div style={{ display: 'flex', gap: 9 }}>
            {[['hilang', 'Kehilangan', 'var(--coral)'], ['temuan', 'Menemukan', 'var(--lime)']].map(([k, l, col]) => (
              <button key={k} onClick={() => setKind(k)} style={{ flex: 1, padding: '13px', borderRadius: 'var(--r-md)', cursor: 'pointer', fontFamily: 'var(--font)', fontWeight: 700, fontSize: 14, border: '2px solid ' + (kind === k ? col : 'var(--border)'), background: kind === k ? col + '14' : 'var(--surface)', color: kind === k ? col : 'var(--text-2)' }}>{l}</button>
            ))}
          </div>
        </div>
        <div>
          <Lbl>Jenis barang</Lbl>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {LF_CATS.map(c => { const on = cat === c.key; return (
              <button key={c.key} onClick={() => setCat(c.key)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, padding: '11px 6px', borderRadius: 'var(--r-md)', cursor: 'pointer', border: '2px solid ' + (on ? c.color : 'var(--border)'), background: on ? c.color + '12' : 'var(--surface)', fontFamily: 'var(--font)' }}>
                <Icon name={c.icon} size={20} color={c.color} /><span style={{ fontSize: 10.5, fontWeight: 700, color: on ? c.color : 'var(--text-2)' }}>{c.label}</span>
              </button>); })}
          </div>
        </div>
        <div>
          <Lbl>Foto</Lbl>
          <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
          <button onClick={() => fileRef.current && fileRef.current.click()} style={{ width: '100%', height: photoPrev ? 160 : 92, borderRadius: 'var(--r-md)', border: photoPrev ? 'none' : '2px dashed var(--border-strong)', background: 'var(--surface-2)', display: 'grid', placeItems: 'center', cursor: 'pointer', overflow: 'hidden', padding: 0 }}>
            {photoPrev ? <img src={photoPrev} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: 'var(--text-3)' }}><Icon name="camera" size={24} color="var(--text-3)" /><span style={{ fontSize: 12.5, fontWeight: 600 }}>Ganti foto</span></span>}
          </button>
        </div>
        <div><Lbl>Judul</Lbl><Inp value={title} onChange={e => { setTitle(e.target.value); setErr(''); }} /></div>
        <div><Lbl>Deskripsi</Lbl><textarea value={body} maxLength={600} onChange={e => setBody(e.target.value)} rows={3} style={{ ...fld, resize: 'none', lineHeight: 1.5 }} /></div>
        <div><Lbl>Lokasi terakhir</Lbl><Inp value={loc} onChange={e => setLoc(e.target.value)} /></div>
        <div><Lbl>Cluster <span style={{ color: 'var(--text-3)', fontWeight: 500 }}>(opsional)</span></Lbl>
          <select value={clusterId} onChange={e => setClusterId(e.target.value)} style={{ ...fld, appearance: 'none' }}><option value="">Pilih cluster</option>{clusters.map(cl => <option key={cl.id} value={cl.id}>{cl.name}</option>)}</select></div>
        <div><Lbl>Kontak WhatsApp</Lbl><Inp value={wa} onChange={e => setWa(e.target.value)} placeholder="08xxxxxxxxxx" type="tel" /></div>
        {err && <div style={{ display: 'flex', alignItems: 'center', gap: 8, 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>
    </FlowShell>
  );
}

Object.assign(window, { LostFoundScreen, LFDetailSheet, LostFoundFlow, LostFoundEditFlow, LF_CATS });
