// contact.jsx — ContactModal (buyer asks seller a question)
// Lives outside admin.jsx so site pages can mount it without loading the admin shell.

(function() {
  const { useState: _cS } = React;

  function ContactModal({ listing, onClose }) {
    const [channel, setChannel] = _cS('platform');
    const [name, setName] = _cS('');
    const [contact, setContact] = _cS('');
    const [msg, setMsg] = _cS('');
    const [sent, setSent] = _cS(false);

    // listings can carry the seller's handle as either `handle` (e.g. "@citytrails") or `username`
    const sellerHandle = (listing?.username || listing?.handle || '').replace(/^@/, '') || 'satıcı';

    const send = () => {
      if (!msg.trim() || !name.trim()) return;
      const all = JSON.parse(localStorage.getItem('insta_messages_v1') || '[]');
      all.unshift({
        id: 'msg_' + Math.random().toString(36).slice(2, 9),
        listingId: listing?.id || null,
        username: sellerHandle,
        buyer: name,
        contact,
        channel,
        message: msg,
        createdAt: new Date().toISOString(),
        status: 'new',
      });
      localStorage.setItem('insta_messages_v1', JSON.stringify(all));
      setSent(true);
    };

    const stop = e => e.stopPropagation();
    const channels = [
      { id: 'platform', label: 'Platform mesajı', sub: 'Cevap e-postanla gelir', k: '✎', c: 'var(--accent)' },
      { id: 'whatsapp', label: 'WhatsApp', sub: 'Anlık yazışma', k: 'W', c: '#25d366' },
      { id: 'telegram', label: 'Telegram', sub: 'Anlık yazışma', k: 'T', c: '#229ED9' },
    ];

    return (
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'oklch(0.15 0.03 320 / 0.55)',
        backdropFilter: 'blur(8px)', display: 'grid', placeItems: 'center', zIndex: 100, padding: 20,
      }}>
        <div onClick={stop} className="is-card" style={{ width: '100%', maxWidth: 460, padding: 24, position: 'relative' }}>
          <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, background: 'var(--chip)', border: 0, width: 32, height: 32, borderRadius: 8, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
            <Icon name="x" size={14}/>
          </button>

          {sent ? (
            <div style={{ textAlign: 'center', padding: '24px 8px' }}>
              <div style={{ width: 64, height: 64, margin: '0 auto 14px', borderRadius: '50%', background: 'var(--g1)', display: 'grid', placeItems: 'center', color: '#fff' }}>
                <Icon name="check" size={28} color="#fff" strokeWidth={2.4}/>
              </div>
              <h3 style={{ margin: '0 0 8px', fontFamily: 'var(--font-display)' }}>Mesajın gönderildi</h3>
              <p style={{ color: 'var(--ink-3)', fontSize: 14, margin: '0 0 20px' }}>
                Satıcı genelde 1 saat içinde dönüş yapıyor. {channel === 'platform' ? 'Cevap e-postana gelecek.' : 'Birazdan ' + (channel === 'whatsapp' ? 'WhatsApp' : 'Telegram') + ' üzerinden ulaşılacak.'}
              </p>
              <button onClick={onClose} className="is-btn is-btn-primary" style={{ padding: '12px 22px' }}>Tamam</button>
            </div>
          ) : (
            <>
              <div className="is-kicker" style={{ marginBottom: 6 }}>İletişim</div>
              <h3 style={{ margin: '0 0 4px', fontFamily: 'var(--font-display)', fontSize: 22, letterSpacing: '-0.01em' }}>
                @{sellerHandle}'ya soru sor
              </h3>
              <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: '0 0 18px' }}>
                Hesap, devir veya pazarlık hakkında ne sormak istersen yaz.
              </p>

              <label className="is-kicker" style={{ display: 'block', marginBottom: 8 }}>Kanal</label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, marginBottom: 16 }}>
                {channels.map(c => {
                  const on = channel === c.id;
                  return (
                    <button key={c.id} onClick={() => setChannel(c.id)} style={{
                      border: on ? '1.5px solid var(--accent)' : '1px solid var(--line-2)',
                      background: on ? 'color-mix(in oklab, var(--accent) 8%, var(--surface))' : 'var(--surface)',
                      borderRadius: 12, padding: '10px 8px', cursor: 'pointer', textAlign: 'left',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                        <span style={{ width: 18, height: 18, borderRadius: 5, background: c.c, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>{c.k}</span>
                        <span style={{ fontSize: 12, fontWeight: 600 }}>{c.label}</span>
                      </div>
                      <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{c.sub}</div>
                    </button>
                  );
                })}
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
                <div>
                  <label className="is-kicker" style={{ display: 'block', marginBottom: 6 }}>Adın</label>
                  <input value={name} onChange={e => setName(e.target.value)} placeholder="Ahmet Y." className="is-input"/>
                </div>
                <div>
                  <label className="is-kicker" style={{ display: 'block', marginBottom: 6 }}>{channel === 'platform' ? 'E-posta' : channel === 'whatsapp' ? 'Telefon' : 'Kullanıcı adı'}</label>
                  <input value={contact} onChange={e => setContact(e.target.value)} placeholder={channel === 'platform' ? 'sen@mail.com' : channel === 'whatsapp' ? '+90 5xx xxx xx xx' : '@kullaniciadi'} className="is-input"/>
                </div>
              </div>

              <label className="is-kicker" style={{ display: 'block', marginBottom: 6 }}>Mesajın</label>
              <textarea value={msg} onChange={e => setMsg(e.target.value)} rows={4} placeholder="Hesabın etkileşim oranı son 30 günde nasıl? Pazarlık payı var mı?" className="is-input" style={{ resize: 'vertical', minHeight: 90, fontFamily: 'inherit' }}/>

              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, padding: 10, background: 'var(--chip)', borderRadius: 10, fontSize: 11, color: 'var(--ink-2)' }}>
                <Icon name="shield" size={14} color="var(--accent)"/>
                <span>InstaSatış mesajları satıcıyla aranda taşır. Şifre/kart paylaşma.</span>
              </div>

              <div style={{ display: 'flex', gap: 8, marginTop: 18, justifyContent: 'flex-end' }}>
                <button onClick={onClose} className="is-btn is-btn-ghost" style={{ padding: '12px 18px' }}>Vazgeç</button>
                <button onClick={send} disabled={!msg.trim() || !name.trim()} className="is-btn is-btn-primary" style={{ padding: '12px 22px', opacity: (!msg.trim() || !name.trim()) ? 0.5 : 1 }}>
                  <Icon name="send" size={14} color="#fff"/> Gönder
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    );
  }

  window.ContactModal = ContactModal;
})();
