/* ============================================================
   CENSA — Emploi
   Deux vues : Offres (rechercher) · Publier une annonce.
   Les annonces de l'utilisateur sont persistées dans localStorage.
   ============================================================ */

function readJobs() {
  try { const v = JSON.parse(localStorage.getItem('censa_jobs')); return Array.isArray(v) ? v : []; }
  catch (e) { return []; }
}

function JobCard({ j, onApply, applied, onDelete }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 13 }}>
        <div style={{ width: 46, height: 46, borderRadius: 12, flex: '0 0 auto', display: 'grid', placeItems: 'center', background: 'var(--glow)', color: 'var(--accent)' }}>
          <Icon name="work" size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 16.5, fontFamily: 'var(--font-brand)', textWrap: 'pretty' }}>{L(j.title)}</div>
          <div style={{ fontSize: 13.5, color: 'var(--text-dim)', marginTop: 2 }}>
            {j.company}{j.mine && <span className="mono" style={{ marginLeft: 8, fontSize: 10.5, color: 'var(--accent)', border: '1px solid var(--border-br)', padding: '2px 7px', borderRadius: 6, letterSpacing: '.06em' }}>{L({ fr: 'VOTRE ANNONCE', en: 'YOUR POST' })}</span>}
          </div>
        </div>
        {j.mine && onDelete && (
          <button className="iconbtn" title={L({ fr: 'Retirer l\u2019annonce', en: 'Remove post' })} onClick={() => onDelete(j.id)}><Icon name="trash" size={16} /></button>
        )}
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 13 }}>
        <span className="mono" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--text-dim)', background: 'var(--surface-2)', border: '1px solid var(--border)', padding: '5px 10px', borderRadius: 999 }}>
          <Icon name="loc" size={13} /> {L(j.location)}</span>
        <span className="mono" style={{ fontSize: 11.5, color: 'var(--text-dim)', background: 'var(--surface-2)', border: '1px solid var(--border)', padding: '5px 10px', borderRadius: 999 }}>{L(j.type)}</span>
        {j.salary && <span className="mono" style={{ fontSize: 11.5, color: 'var(--accent)', background: 'var(--glow)', border: '1px solid var(--border-br)', padding: '5px 10px', borderRadius: 999 }}>{j.salary}</span>}
      </div>

      <p style={{ marginTop: 12, fontSize: 14, color: 'var(--text-dim)', lineHeight: 1.55, textWrap: 'pretty' }}>{L(j.desc)}</p>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 14 }}>
        <button className={'btn' + (applied ? '' : ' btn-primary')} disabled={applied} onClick={() => onApply(j.id)} style={{ padding: '9px 18px' }}>
          {applied ? <><Icon name="check" size={16} sw={2.4} /> {L({ fr: 'Candidature envoyée', en: 'Application sent' })}</> : <><Icon name="send" size={15} /> {L({ fr: 'Postuler', en: 'Apply' })}</>}
        </button>
        <span className="mono" style={{ fontSize: 11.5, color: 'var(--text-faint)' }}>{L(j.posted)}</span>
      </div>
    </div>
  );
}

function PostJobForm({ onPublish }) {
  const [title, setTitle] = useState('');
  const [company, setCompany] = useState('');
  const [location, setLocation] = useState('');
  const [type, setType] = useState('CDI');
  const [salary, setSalary] = useState('');
  const [desc, setDesc] = useState('');
  const valid = title.trim() && company.trim() && desc.trim();

  const submit = () => {
    if (!valid) return;
    onPublish({
      id: 'uj_' + Date.now().toString(36), mine: true,
      title: { fr: title.trim(), en: title.trim() }, company: company.trim(),
      location: { fr: location.trim() || 'Non précisé', en: location.trim() || 'Unspecified' },
      type: { fr: type, en: type }, salary: salary.trim(),
      desc: { fr: desc.trim(), en: desc.trim() }, posted: { fr: 'à l\u2019instant', en: 'just now' },
    });
    setTitle(''); setCompany(''); setLocation(''); setSalary(''); setDesc(''); setType('CDI');
  };

  return (
    <div className="card" style={{ padding: 20 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="field">
          <label>{L({ fr: 'Intitulé du poste', en: 'Job title' })}</label>
          <input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder={L({ fr: 'ex. Analyste de données', en: 'e.g. Data analyst' })} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="field">
            <label>{L({ fr: 'Entreprise', en: 'Company' })}</label>
            <input className="input" value={company} onChange={(e) => setCompany(e.target.value)} placeholder="CENSA" />
          </div>
          <div className="field">
            <label>{L({ fr: 'Lieu', en: 'Location' })}</label>
            <input className="input" value={location} onChange={(e) => setLocation(e.target.value)} placeholder={L({ fr: 'Télétravail', en: 'Remote' })} />
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="field">
            <label>{L({ fr: 'Type de contrat', en: 'Contract type' })}</label>
            <select className="input" value={type} onChange={(e) => setType(e.target.value)} style={{ appearance: 'auto' }}>
              <option>CDI</option><option>CDD</option><option>Freelance</option><option>Stage</option><option>Alternance</option>
            </select>
          </div>
          <div className="field">
            <label>{L({ fr: 'Rémunération (option)', en: 'Pay (optional)' })}</label>
            <input className="input" value={salary} onChange={(e) => setSalary(e.target.value)} placeholder="3 000 $/mois" />
          </div>
        </div>
        <div className="field">
          <label>{L({ fr: 'Description', en: 'Description' })}</label>
          <textarea className="input" value={desc} onChange={(e) => setDesc(e.target.value)} rows={4}
            placeholder={L({ fr: 'Missions, profil recherché…', en: 'Responsibilities, ideal profile…' })} style={{ resize: 'vertical', minHeight: 96, lineHeight: 1.5 }} />
        </div>
        <button className="btn btn-primary" onClick={submit} disabled={!valid} style={{ padding: '12px 0', opacity: valid ? 1 : .55 }}>
          <Icon name="work" size={16} /> {L({ fr: 'Publier l\u2019annonce', en: 'Publish job' })}</button>
      </div>
    </div>
  );
}

function Jobs({ t }) {
  const [tab, setTab] = useState('browse');
  const [query, setQuery] = useState('');
  const [mine, setMine] = useState(readJobs);
  const [applied, setApplied] = useState([]);
  const [flash, setFlash] = useState('');

  const all = [...mine, ...JOBS];
  const q = query.trim().toLowerCase();
  const list = q ? all.filter(j => (L(j.title) + ' ' + j.company + ' ' + L(j.location) + ' ' + L(j.type)).toLowerCase().includes(q)) : all;

  const publish = (job) => {
    const next = [job, ...mine]; setMine(next);
    try { localStorage.setItem('censa_jobs', JSON.stringify(next)); } catch (e) {}
    setTab('browse'); setFlash(L({ fr: 'Annonce publiée.', en: 'Job published.' })); setTimeout(() => setFlash(''), 3500);
  };
  const removeJob = (id) => { const next = mine.filter(j => j.id !== id); setMine(next); try { localStorage.setItem('censa_jobs', JSON.stringify(next)); } catch (e) {} };
  const apply = (id) => setApplied(a => a.includes(id) ? a : [...a, id]);

  return (
    <div className="animate-in">
      <SectionHead icon="work" title={L({ fr: 'Emploi', en: 'Jobs' })}
        sub={L({ fr: 'Trouvez un poste ou publiez une annonce.', en: 'Find a role or post a listing.' })} />

      <div style={{ display: 'flex', borderBottom: '1px solid var(--border)' }}>
        <button className={'tab' + (tab === 'browse' ? ' active' : '')} onClick={() => setTab('browse')}>{L({ fr: 'Offres', en: 'Listings' })}</button>
        <button className={'tab' + (tab === 'post' ? ' active' : '')} onClick={() => setTab('post')}>{L({ fr: 'Publier une annonce', en: 'Post a job' })}</button>
      </div>

      {tab === 'browse' ? (
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={18} style={{ position: 'absolute', left: 14, top: 14, color: 'var(--text-faint)' }} />
            <input className="input" value={query} onChange={(e) => setQuery(e.target.value)}
              placeholder={L({ fr: 'Rechercher un poste, une entreprise, un lieu…', en: 'Search a role, company, location…' })}
              style={{ paddingLeft: 42, borderRadius: 999 }} />
          </div>
          {flash && <div className="mono" style={{ display: 'inline-flex', alignSelf: 'flex-start', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: 'var(--good)', background: 'oklch(0.78 0.14 150 / .14)', padding: '6px 12px', borderRadius: 999 }}><Icon name="check" size={14} sw={2.6} /> {flash}</div>}
          {list.length ? list.map(j => (
            <JobCard key={j.id} j={j} applied={applied.includes(j.id)} onApply={apply} onDelete={removeJob} />
          )) : (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: 'var(--text-faint)' }}>
              <Icon name="work" size={30} style={{ opacity: .5 }} />
              <p className="mono" style={{ marginTop: 12, fontSize: 13 }}>{L({ fr: 'Aucune offre ne correspond à votre recherche.', en: 'No listing matches your search.' })}</p>
            </div>
          )}
        </div>
      ) : (
        <div style={{ padding: 18 }}>
          <PostJobForm onPublish={publish} />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Jobs, JobCard, PostJobForm });
