// screens-misc.jsx — create listing, alerts, referral, admin

// Sous-composant DÉFINI EN DEHORS pour éviter le bug focus React
function ListingField({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.5 }}>{label}</div>
      {children}
    </div>
  );
}

function CreateListingScreen({ lang, t, onBack, onPublish }) {
  const me = (window.TrustaAuth && window.TrustaAuth.getUser()) || null;
  const [kind, setKind] = React.useState('demand');     // demand = je cherche, offer = je propose
  const [cats, setCats] = React.useState(['housekeeping']); // multi-sélection
  const [title, setTitle] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [cities, setCities] = React.useState(me && me.city ? [me.city] : []); // chips
  const [cityInput, setCityInput] = React.useState('');
  const [rate, setRate] = React.useState('');
  const [unit, setUnit] = React.useState('hour');
  const [photos, setPhotos] = React.useState([]);       // [{url, name}]
  const [uploading, setUploading] = React.useState(false);
  const [publishing, setPublishing] = React.useState(false);
  const [error, setError] = React.useState(null);
  const fileRef = React.useRef(null);

  const inputStyle = {
    height: 48, borderRadius: 12, background: COLORS.card,
    border: `1px solid ${COLORS.borderSoft}`, padding: '0 14px',
    color: '#fff', fontFamily: 'Inter', fontSize: 14, outline: 'none',
    boxSizing: 'border-box', width: '100%',
  };

  const onPickFiles = async (e) => {
    const files = Array.from(e.target.files || []);
    if (fileRef.current) fileRef.current.value = ''; // reset tout de suite pour pouvoir re-sélectionner
    if (!files.length) return;
    if (photos.length + files.length > 6) {
      setError(lang === 'ka' ? 'მაქს. 6 ფოტო' : 'Max 6 photos');
      return;
    }
    setError(null);
    setUploading(true);
    const uploaded = [];
    try {
      for (const f of files) {
        if (!window.API_AVAILABLE) {
          uploaded.push({ url: URL.createObjectURL(f), name: f.name });
          continue;
        }
        const res = await window.TrustaAPI.uploadListingPhoto(f);
        uploaded.push({ url: res.url, name: f.name });
      }
      // ⚠️ functional update : on ne touche PAS la state directement
      setPhotos(prev => [...prev, ...uploaded]);
    } catch (err) {
      console.error('upload failed', err);
      // on garde quand même celles déjà uploadées avec succès
      if (uploaded.length) setPhotos(prev => [...prev, ...uploaded]);
      setError(window.errorMessage ? window.errorMessage(err, lang) : (err.message || 'Upload error'));
    } finally {
      setUploading(false);
    }
  };

  const removePhoto = (i) => {
    setPhotos(prev => prev.filter((_, idx) => idx !== i));
  };

  // === Helpers villes (chips) ===
  const addCity = (v) => {
    const c = (v || cityInput).trim();
    if (!c || c.length < 2) return;
    if (cities.includes(c)) { setCityInput(''); return; }
    if (cities.length >= 10) { setError(lang === 'ka' ? 'მაქს. 10 ქალაქი' : 'Max 10 villes'); return; }
    setCities([...cities, c]);
    setCityInput('');
  };
  const removeCity = (i) => {
    const next = [...cities]; next.splice(i, 1); setCities(next);
  };
  const toggleCat = (id) => {
    if (cats.includes(id)) {
      if (cats.length === 1) return; // garde au moins une cat sélectionnée
      setCats(cats.filter(c => c !== id));
    } else {
      if (cats.length >= 5) { setError(lang === 'ka' ? 'მაქს. 5 კატეგორია' : 'Max 5 catégories'); return; }
      setCats([...cats, id]);
    }
  };

  const submit = async () => {
    if (publishing) return;
    setError(null);
    // Si une ville est tapée mais pas validée par Entrée → la prendre quand même
    let finalCities = [...cities];
    const pending = cityInput.trim();
    if (pending.length >= 2 && !finalCities.includes(pending)) finalCities.push(pending);

    if (title.trim().length < 4)  { setError(lang === 'ka' ? 'სათაური ძალიან მოკლეა' : 'Titre trop court (4+ caractères)'); return; }
    if (finalCities.length === 0) { setError(lang === 'ka' ? 'მიუთითეთ მინ. 1 ქალაქი' : 'Indique au moins une ville'); return; }
    if (cats.length === 0)        { setError(lang === 'ka' ? 'აირჩიე კატეგორია' : 'Choisis une catégorie'); return; }

    if (!window.API_AVAILABLE) { onPublish(); return; }

    setPublishing(true);
    try {
      await window.TrustaAPI.createListing({
        kind, categories: cats,
        title: title.trim(),
        description: desc.trim() || undefined,
        cities: finalCities,
        price_amount: rate ? parseFloat(rate) : undefined,
        price_unit: unit,
        photos: photos.map(p => p.url),
      });
      onPublish();
    } catch (err) {
      console.error('createListing failed', err);
      setError(window.errorMessage ? window.errorMessage(err, lang) : (err.message || 'Erreur'));
      setPublishing(false);
    }
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={onBack} title={t('create_listing')} />
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 24px 110px', display: 'flex', flexDirection: 'column', gap: 18 }}>

        {/* Kind toggle */}
        <ListingField label={t('kind')}>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { id: 'demand', label: t('kind_demand') },
              { id: 'offer',  label: t('kind_offer') },
            ].map(k => {
              const a = kind === k.id;
              return (
                <button key={k.id} onClick={() => setKind(k.id)} style={{
                  flex: 1, height: 44, borderRadius: 12,
                  background: a ? COLORS.goldSoft : COLORS.card,
                  border: `1px solid ${a ? COLORS.gold : COLORS.borderSoft}`,
                  color: a ? COLORS.gold : COLORS.text2,
                  fontFamily: 'Inter', fontSize: 12, fontWeight: a ? 700 : 500,
                  cursor: 'pointer',
                }}>{k.label}</button>
              );
            })}
          </div>
        </ListingField>

        {/* Photos */}
        <ListingField label={t('photos') + ' ' + photos.length + '/6'}>
          <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" multiple onChange={onPickFiles} style={{ display: 'none' }} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {photos.map((p, i) => (
              <div key={i} style={{ position: 'relative', width: 80, height: 80, borderRadius: 10, background: `url(${p.url}) center/cover`, border: `1px solid ${COLORS.borderSoft}` }}>
                <button onClick={() => removePhoto(i)} style={{
                  position: 'absolute', top: 4, right: 4, width: 22, height: 22, borderRadius: 11,
                  background: 'rgba(0,0,0,0.7)', border: 'none', color: '#fff', cursor: 'pointer', fontSize: 12,
                }}>×</button>
              </div>
            ))}
            {photos.length < 6 && (
              <button onClick={() => fileRef.current?.click()} disabled={uploading} style={{
                width: 80, height: 80, borderRadius: 10,
                background: COLORS.card, border: `1.5px dashed ${COLORS.gold}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: uploading ? 'wait' : 'pointer', opacity: uploading ? 0.5 : 1,
              }}>
                <span style={{ color: COLORS.gold, fontSize: 22 }}>{uploading ? '…' : '+'}</span>
              </button>
            )}
          </div>
        </ListingField>

        <ListingField label={t('title_field')}>
          <input value={title} onChange={e => setTitle(e.target.value)} placeholder={t('title_ph')} style={inputStyle} maxLength={200} />
        </ListingField>

        <ListingField label={t('description_field')}>
          <textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder={t('description_ph')} style={{
            ...inputStyle, height: 96, padding: 14, resize: 'none',
          }} maxLength={2000} />
        </ListingField>

        <ListingField label={t('cities_field') + (cities.length ? ' · ' + cities.length : '')}>
          {/* Chips villes */}
          {cities.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
              {cities.map((c, i) => (
                <div key={c + i} style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  padding: '6px 10px', borderRadius: 999,
                  background: COLORS.goldSoft, border: `1px solid ${COLORS.gold}`,
                  color: COLORS.gold, fontFamily: 'Inter', fontSize: 12, fontWeight: 600,
                }}>
                  {c}
                  <button onClick={() => removeCity(i)} style={{
                    width: 16, height: 16, borderRadius: 8, padding: 0,
                    background: 'rgba(0,0,0,0.4)', border: 'none', color: COLORS.gold,
                    fontSize: 10, lineHeight: 1, cursor: 'pointer',
                  }}>×</button>
                </div>
              ))}
            </div>
          )}
          {/* Input + bouton add */}
          <div style={{ display: 'flex', gap: 6 }}>
            <input
              value={cityInput}
              onChange={e => setCityInput(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addCity(); }
                if (e.key === 'Backspace' && !cityInput && cities.length) { removeCity(cities.length - 1); }
              }}
              placeholder={cities.length ? (lang === 'ka' ? '+ ახალი ქალაქი' : '+ Autre ville') : t('city_ph')}
              style={{ ...inputStyle, flex: 1 }}
            />
            <button onClick={() => addCity()} disabled={cityInput.trim().length < 2} style={{
              width: 48, height: 48, borderRadius: 12,
              background: cityInput.trim().length >= 2 ? COLORS.gold : COLORS.card,
              border: `1px solid ${cityInput.trim().length >= 2 ? COLORS.gold : COLORS.borderSoft}`,
              color: cityInput.trim().length >= 2 ? '#0A0A0A' : COLORS.text3,
              fontSize: 22, fontWeight: 600, cursor: cityInput.trim().length >= 2 ? 'pointer' : 'default',
            }}>+</button>
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, marginTop: 4 }}>
            {lang === 'ka'
              ? 'აკრიფე ქალაქი და დააჭირე Enter (მაქს. 10)'
              : 'Tape une ville et appuie sur Entrée (max 10)'}
          </div>
        </ListingField>

        <ListingField label={t('categories_field') + (cats.length ? ' · ' + cats.length + '/5' : '')}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {CATEGORIES.filter(c => c.id !== 'all').map(c => {
              const a = cats.includes(c.id);
              return (
                <button key={c.id} onClick={() => toggleCat(c.id)} style={{
                  height: 34, padding: '0 12px', borderRadius: 10,
                  background: a ? COLORS.goldSoft : COLORS.card,
                  border: `1px solid ${a ? COLORS.gold : COLORS.borderSoft}`,
                  color: a ? COLORS.gold : COLORS.text2,
                  fontFamily: 'Inter', fontSize: 12, fontWeight: a ? 700 : 500,
                  cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4,
                }}>
                  {a && <span style={{ fontSize: 10 }}>✓</span>}
                  {t('cat_' + c.id)}
                </button>
              );
            })}
          </div>
        </ListingField>

        <ListingField label={t('rate')}>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ position: 'relative', flex: 1 }}>
              <input value={rate} onChange={e => setRate(e.target.value)} placeholder={t('rate_ph')} style={inputStyle} type="number" min="0" />
              <div style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', fontFamily: 'Inter', fontSize: 13, color: COLORS.text3 }}>€</div>
            </div>
            <select value={unit} onChange={e => setUnit(e.target.value)} style={{
              ...inputStyle, width: 110, paddingRight: 8, cursor: 'pointer',
            }}>
              <option value="hour">{t('unit_hour')}</option>
              <option value="day">{t('unit_day')}</option>
              <option value="job">{t('unit_job')}</option>
            </select>
          </div>
        </ListingField>

        {error && (
          <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.red, textAlign: 'center', padding: '4px 8px' }}>
            {error}
          </div>
        )}
      </div>
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 20px 28px', background: 'linear-gradient(180deg, rgba(11,11,11,0) 0%, #0B0B0B 30%)' }}>
        <GoldButton onClick={submit} disabled={publishing || uploading}>
          {publishing ? t('publishing') : t('publish')}
        </GoldButton>
      </div>
    </div>
  );
}

function AlertsScreen({ lang, t, onOpenListing, onOpenChat }) {
  const [items, setItems] = React.useState(null);
  const [error, setError] = React.useState(null);

  const load = React.useCallback(async () => {
    if (!window.API_AVAILABLE) { setItems([]); return; }
    try {
      const res = await window.TrustaAPI.listNotifications();
      setItems(res.items || []);
      // Marque tout comme lu après affichage (UX inbox classique)
      if (res.unread > 0) {
        try { await window.TrustaAPI.markAllNotificationsRead(); } catch (e) {}
        if (window.TrustaNotifStore) window.TrustaNotifStore.refresh();
      }
    } catch (e) {
      setError(e); setItems([]);
    }
  }, []);

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

  const fmtTime = (iso) => {
    if (!iso) return '';
    const d = new Date(iso.replace(' ', 'T') + 'Z');
    const diff = Math.floor((Date.now() - d.getTime()) / 1000);
    if (diff < 60) return lang === 'ka' ? 'ახლა' : 'maint.';
    if (diff < 3600) return Math.floor(diff / 60) + (lang === 'ka' ? ' წ.' : ' min');
    if (diff < 86400) return Math.floor(diff / 3600) + 'h';
    if (diff < 7 * 86400) return Math.floor(diff / 86400) + (lang === 'ka' ? ' დღე' : ' j');
    return d.toLocaleDateString(lang === 'ka' ? 'ka-GE' : 'fr-FR');
  };

  const Icon = ({ kind }) => {
    const props = { width: 18, height: 18, fill: 'none', stroke: COLORS.gold, strokeWidth: 1.5 };
    if (kind === 'message') return <svg viewBox="0 0 18 18" {...props}><path d="M2 4 H16 V13 H10 L6 16 V13 H2 Z" strokeLinejoin="round" /></svg>;
    if (kind === 'favorite_listing' || kind === 'favorite_profile')
      return <svg viewBox="0 0 24 24" {...props}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" strokeLinejoin="round" /></svg>;
    return <svg viewBox="0 0 18 18" {...props}><circle cx="9" cy="9" r="6" /></svg>;
  };

  const renderText = (n) => {
    const actor = n.payload?.actor_name || (lang === 'ka' ? 'მომხმარებელი' : 'Quelqu\'un');
    if (n.kind === 'favorite_listing') {
      const t1 = lang === 'ka'
        ? `${actor}-მ მოიწონა შენი განცხადება`
        : `${actor} a ajouté votre annonce aux favoris`;
      const t2 = n.payload?.listing_title || '';
      return { title: t1, sub: t2 };
    }
    if (n.kind === 'favorite_profile') {
      return {
        title: lang === 'ka'
          ? `${actor}-მ თქვენი პროფილი ფავორიტებში დაამატა`
          : `${actor} a ajouté votre profil aux favoris`,
        sub: '',
      };
    }
    if (n.kind === 'message') {
      return {
        title: lang === 'ka' ? `ახალი შეტყობინება — ${actor}` : `Nouveau message — ${actor}`,
        sub: n.payload?.preview || '',
      };
    }
    return { title: n.kind, sub: '' };
  };

  const handleClick = (n) => {
    if (n.kind === 'favorite_listing' && n.payload?.listing_id && onOpenListing) {
      // On charge l'annonce par son ID
      window.TrustaAPI.getListing(n.payload.listing_id)
        .then(l => onOpenListing(l))
        .catch(() => {});
    } else if (n.kind === 'message' && n.payload?.conversation_id && onOpenChat) {
      onOpenChat({ id: n.payload.conversation_id, peer_id: n.payload.actor_id, peer_name: n.payload.actor_name });
    }
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header big title={t('nav_alerts')} />
      <div style={{ flex: 1, overflow: 'auto', padding: '4px 16px 110px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {items === null ? (
          <div style={{ textAlign: 'center', padding: 60, color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
            {lang === 'ka' ? 'იტვირთება...' : 'Chargement...'}
          </div>
        ) : items.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px', color: COLORS.text3, fontFamily: 'Inter' }}>
            <div style={{ fontSize: 40, marginBottom: 16 }}>🔔</div>
            <div style={{ color: '#fff', fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
              {lang === 'ka' ? 'შეტყობინებები არაა' : 'Pas de notifications'}
            </div>
          </div>
        ) : items.map((n) => {
          const txt = renderText(n);
          const unread = !n.read_at;
          return (
            <button key={n.id} onClick={() => handleClick(n)} style={{
              display: 'flex', gap: 12, padding: 14, textAlign: 'left',
              background: unread ? 'rgba(212,175,55,0.05)' : COLORS.card,
              borderRadius: 14, border: `1px solid ${unread ? 'rgba(212,175,55,0.18)' : COLORS.borderSoft}`,
              cursor: 'pointer', width: '100%',
            }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: COLORS.goldSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon kind={n.kind} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                  <div style={{ fontFamily: 'Inter', fontSize: 13, color: '#fff', fontWeight: 600, flex: 1 }}>{txt.title}</div>
                  <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, flexShrink: 0 }}>{fmtTime(n.created_at)}</div>
                </div>
                {txt.sub && (
                  <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text2, marginTop: 4, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{txt.sub}</div>
                )}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function ReferralScreen({ lang, t, onBack }) {
  const [copied, setCopied] = React.useState(false);
  const code = 'TRUSTA-ANIG-X42';
  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={onBack} title={t('invite')} />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px 110px' }}>
        <div style={{
          padding: '28px 22px', borderRadius: 22,
          background: 'linear-gradient(160deg, #1A1A1A 0%, #0F0F0F 100%)',
          border: `1px solid ${COLORS.gold}`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle, rgba(212,175,55,0.25), transparent 70%)' }} />
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
            <TrustaLogo size={48} />
          </div>
          <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 22, color: '#fff', textAlign: 'center', fontWeight: 600 }}>
            {t('invite_friends')}
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text2, textAlign: 'center', marginTop: 8, lineHeight: 1.5 }}>
            {t('invite_subtitle')}
          </div>
          <div style={{ marginTop: 22, padding: 14, borderRadius: 12, background: COLORS.bg, border: `1px dashed ${COLORS.gold}` }}>
            <div style={{ fontFamily: 'Inter', fontSize: 10, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.6, textAlign: 'center' }}>
              {t('your_code')}
            </div>
            <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 22, color: COLORS.gold, textAlign: 'center', marginTop: 4, letterSpacing: 2 }}>
              {code}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
            <button onClick={() => { navigator.clipboard?.writeText(code); setCopied(true); setTimeout(() => setCopied(false), 1500); }} style={{
              flex: 1, height: 44, borderRadius: 12,
              background: 'transparent', border: `1px solid ${COLORS.gold}`, color: COLORS.gold,
              fontFamily: 'Inter', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            }}>{copied ? '✓' : t('copy_code')}</button>
            <button style={{
              flex: 1, height: 44, borderRadius: 12,
              background: 'linear-gradient(180deg, #E4C25C, #B6932B)', border: 'none', color: '#0A0A0A',
              fontFamily: 'Inter', fontSize: 13, fontWeight: 700, cursor: 'pointer',
            }}>{t('share_code')}</button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          {[
            { val: '7', lab: t('invited_count') },
            { val: '€70', lab: t('earned') },
          ].map((s, i) => (
            <div key={i} style={{ flex: 1, padding: 18, background: COLORS.card, borderRadius: 14, border: `1px solid ${COLORS.borderSoft}`, textAlign: 'center' }}>
              <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 28, color: COLORS.gold, fontWeight: 600 }}>{s.val}</div>
              <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.4, marginTop: 4 }}>{s.lab}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.CreateListingScreen = CreateListingScreen;
window.AlertsScreen = AlertsScreen;
window.ReferralScreen = ReferralScreen;
