// Site Documentation — תיעוד אתר כללי
(function(){
const { useState, useRef, useEffect } = React;

const CATEGORIES = [
  { k:'general',     label:'כללי',              icon:'📸' },
  { k:'structure',   label:'שלד / קונסטרוקציה', icon:'🏗️' },
  { k:'finishing',   label:'גמרים',             icon:'🪣' },
  { k:'systems',     label:'מערכות',            icon:'⚙️' },
  { k:'safety',      label:'בטיחות',            icon:'⛑️' },
  { k:'progress',    label:'התקדמות',           icon:'📈' },
  { k:'issue',       label:'בעיה / חריגה',      icon:'⚠️' },
  { k:'before_after',label:'לפני / אחרי',       icon:'🔄' },
];

const compressPhoto = (file, cb) => {
  const reader = new FileReader();
  reader.onload = e => {
    const img = new Image();
    img.onload = () => {
      const MAX = 1600;
      const ratio = Math.min(1, MAX / Math.max(img.width, img.height));
      const canvas = document.createElement('canvas');
      canvas.width = Math.round(img.width * ratio);
      canvas.height = Math.round(img.height * ratio);
      canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
      cb(canvas.toDataURL('image/jpeg', 0.82));
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
};

const STORAGE_KEY = 'ybp_site_docs';

const loadDocs = (projectId) => {
  try {
    const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
    return all[projectId] || [];
  } catch { return []; }
};

const saveDocs = (projectId, docs) => {
  try {
    const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
    all[projectId] = docs;
    localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
    window.dispatchEvent(new CustomEvent('ybp-site-docs-change'));
  } catch {}
};

// ── כרטיס תמונה ─────────────────────────────────────────────────────────────
const PhotoCard = ({ doc, onDelete }) => {
  const cat = CATEGORIES.find(c => c.k === doc.category) || CATEGORIES[0];
  return (
    <div style={{ background:'#fff', borderRadius:10, overflow:'hidden', border:'1px solid #e5e7eb', position:'relative' }}>
      <img src={doc.photo} alt="" style={{ width:'100%', aspectRatio:'4/3', objectFit:'cover', display:'block' }}/>
      <button onClick={() => { if(window.confirm('מחק תמונה זו?')) onDelete(doc.id); }} style={{
        position:'absolute', top:6, left:6, width:26, height:26, borderRadius:13,
        background:'rgba(0,0,0,0.55)', color:'#fff', border:'none', cursor:'pointer',
        fontSize:13, lineHeight:'26px', textAlign:'center', padding:0,
      }}>✕</button>
      <div style={{ padding:'8px 10px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:3 }}>
          <span style={{ fontSize:13 }}>{cat.icon}</span>
          <span style={{ fontSize:11, fontWeight:700, color:'#1a2c4a' }}>{cat.label}</span>
          <span style={{ marginRight:'auto', fontSize:10, color:'#9ca3af' }}>{doc.date}</span>
        </div>
        {doc.note && <div style={{ fontSize:11.5, color:'#4b5563', lineHeight:1.4 }}>{doc.note}</div>}
      </div>
    </div>
  );
};

// ── Modal הוספת תמונה ────────────────────────────────────────────────────────
const AddPhotoModal = ({ projectId, onClose, onAdded }) => {
  const [photos, setPhotos]     = useState([]);
  const [category, setCategory] = useState('general');
  const [note, setNote]         = useState('');
  const [saving, setSaving]     = useState(false);
  const fileRef = useRef();

  const today = new Date().toLocaleDateString('he-IL');

  const handleFiles = (files) => {
    Array.from(files).forEach(f => compressPhoto(f, ph => {
      setPhotos(prev => [...prev, ph]);
    }));
  };

  const handleSave = () => {
    if (!photos.length) return;
    setSaving(true);
    const existing = loadDocs(projectId);
    const newDocs = photos.map(ph => ({
      id: `sd-${Date.now()}-${Math.random().toString(36).slice(2)}`,
      photo: ph,
      category,
      note,
      date: today,
      projectId,
      createdAt: new Date().toISOString(),
    }));
    saveDocs(projectId, [...existing, ...newDocs]);
    setTimeout(() => { onAdded(); onClose(); }, 200);
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.6)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div style={{ background:'#fff', borderRadius:14, width:'100%', maxWidth:480, maxHeight:'90vh', overflow:'auto', direction:'rtl', fontFamily:'Assistant,sans-serif', boxShadow:'0 20px 60px rgba(0,0,0,0.3)' }}>

        {/* Header */}
        <div style={{ padding:'16px 20px', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <span style={{ fontSize:16, fontWeight:700, color:'#1f2937' }}>📸 הוספת תיעוד אתר</span>
          <button onClick={onClose} style={{ background:'transparent', border:'none', cursor:'pointer', fontSize:20, color:'#6b7280' }}>✕</button>
        </div>

        <div style={{ padding:20, display:'flex', flexDirection:'column', gap:14 }}>

          {/* Upload zone */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:8 }}>תמונות *</label>
            <div
              onDragOver={e => e.preventDefault()}
              onDrop={e => { e.preventDefault(); handleFiles(e.dataTransfer.files); }}
              style={{ border:'2px dashed #cbd5e1', borderRadius:10, padding:'16px 24px', textAlign:'center', background:'#f8fafc', marginBottom:10 }}>
              <div style={{ fontSize:28, marginBottom:6 }}>📷</div>
              <div style={{ fontSize:13, color:'#64748b', fontWeight:600, marginBottom:10 }}>הוסף תמונות לאתר</div>
              <PhotoPickerInline onFiles={files => handleFiles(files)} multiple style={{ justifyContent:'center' }}/>
            </div>

            {photos.length > 0 && (
              <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                {photos.map((ph, i) => (
                  <div key={i} style={{ position:'relative' }}>
                    <img src={ph} alt="" style={{ width:72, height:72, objectFit:'cover', borderRadius:7, border:'1px solid #e5e7eb' }}/>
                    <button onClick={() => setPhotos(prev => prev.filter((_,j)=>j!==i))} style={{
                      position:'absolute', top:-6, left:-6, width:18, height:18, borderRadius:9,
                      background:'#dc2626', color:'#fff', border:'none', cursor:'pointer', fontSize:11, lineHeight:'18px', textAlign:'center', padding:0,
                    }}>✕</button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Category */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:8 }}>קטגוריה</label>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {CATEGORIES.map(c => (
                <button key={c.k} onClick={() => setCategory(c.k)} style={{
                  padding:'6px 12px', borderRadius:20, border:`1px solid ${category===c.k ? '#1a2c4a' : '#e5e7eb'}`,
                  background: category===c.k ? '#1a2c4a' : '#fff',
                  color: category===c.k ? '#fff' : '#4b5563',
                  fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                  display:'flex', alignItems:'center', gap:5,
                }}>{c.icon} {c.label}</button>
              ))}
            </div>
          </div>

          {/* Note */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>הערה (אופציונלי)</label>
            <input value={note} onChange={e => setNote(e.target.value)}
              placeholder="תאר מה מתועד..."
              style={{ width:'100%', padding:'9px 12px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding:'14px 20px', borderTop:'1px solid #e5e7eb', display:'flex', gap:10 }}>
          <button onClick={handleSave} disabled={!photos.length || saving} style={{
            flex:1, padding:'11px', borderRadius:6, border:'none',
            background: photos.length && !saving ? '#1a2c4a' : '#e5e7eb',
            color: photos.length && !saving ? '#fff' : '#9ca3af',
            fontSize:14, fontWeight:700, cursor: photos.length ? 'pointer' : 'default', fontFamily:'inherit',
          }}>{saving ? 'שומר...' : `שמור ${photos.length ? `(${photos.length} תמונות)` : ''}`}</button>
          <button onClick={onClose} style={{
            padding:'11px 18px', borderRadius:6, border:'1px solid #e5e7eb',
            background:'#fff', color:'#6b7280', fontSize:14, cursor:'pointer', fontFamily:'inherit',
          }}>ביטול</button>
        </div>
      </div>
    </div>
  );
};

// ── Main Screen ──────────────────────────────────────────────────────────────
const SiteDocScreen = ({ projectId, onBack }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId) || YBP_DATA.projects[0];
  const [docs, setDocs]           = useState(() => loadDocs(projectId));
  const [showModal, setShowModal] = useState(false);
  const [filterCat, setFilterCat] = useState('all');
  const [search, setSearch]       = useState('');

  useEffect(() => {
    const handler = () => setDocs(loadDocs(projectId));
    window.addEventListener('ybp-site-docs-change', handler);
    return () => window.removeEventListener('ybp-site-docs-change', handler);
  }, [projectId]);

  const filtered = docs.filter(d => {
    if (filterCat !== 'all' && d.category !== filterCat) return false;
    if (search && !d.note?.includes(search)) return false;
    return true;
  }).sort((a,b) => b.createdAt?.localeCompare(a.createdAt||''));

  const deleteDoc = (id) => {
    const updated = docs.filter(d => d.id !== id);
    setDocs(updated);
    saveDocs(projectId, updated);
  };

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl' }}>

      {/* Header */}
      <header style={{
        background:'#1a2c4a', color:'#fff', padding:'14px 20px',
        display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:10,
      }}>
        <button onClick={onBack} style={{
          background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)',
          color:'#fff', width:34, height:34, borderRadius:7, display:'flex',
          alignItems:'center', justifyContent:'center', cursor:'pointer',
        }}>
          <Icon name="chevron" size={16}/>
        </button>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:11, opacity:0.65 }}>{project?.name}</div>
          <div style={{ fontSize:16, fontWeight:700 }}>📸 תיעוד אתר</div>
        </div>
        <div style={{ fontSize:12, opacity:0.7, background:'rgba(255,255,255,0.1)', padding:'4px 10px', borderRadius:10 }}>
          {docs.length} תמונות
        </div>
        <button onClick={() => setShowModal(true)} style={{
          background:'#b5a882', color:'#1a2c4a', border:'none', padding:'9px 18px',
          borderRadius:7, fontSize:13, fontWeight:800, cursor:'pointer', fontFamily:'inherit',
          display:'flex', alignItems:'center', gap:6,
        }}>
          + צלם / העלה
        </button>
      </header>

      {/* Filters */}
      <div style={{ background:'#fff', borderBottom:'1px solid #e5e7eb', padding:'10px 16px', display:'flex', gap:8, flexWrap:'wrap', alignItems:'center' }}>
        <button onClick={() => setFilterCat('all')} style={{
          padding:'5px 12px', borderRadius:16, border:'none', fontSize:12, fontWeight:600,
          cursor:'pointer', fontFamily:'inherit',
          background: filterCat==='all' ? '#1a2c4a' : '#f3f4f6',
          color: filterCat==='all' ? '#fff' : '#4b5563',
        }}>הכל ({docs.length})</button>
        {CATEGORIES.filter(c => docs.some(d => d.category===c.k)).map(c => (
          <button key={c.k} onClick={() => setFilterCat(c.k)} style={{
            padding:'5px 12px', borderRadius:16, border:'none', fontSize:12, fontWeight:600,
            cursor:'pointer', fontFamily:'inherit',
            background: filterCat===c.k ? '#1a2c4a' : '#f3f4f6',
            color: filterCat===c.k ? '#fff' : '#4b5563',
          }}>{c.icon} {c.label} ({docs.filter(d=>d.category===c.k).length})</button>
        ))}
        <input value={search} onChange={e => setSearch(e.target.value)}
          placeholder="חפש לפי הערה..."
          style={{ marginRight:'auto', padding:'5px 10px', border:'1px solid #e5e7eb', borderRadius:16, fontSize:12, fontFamily:'inherit', width:160 }}/>
      </div>

      {/* Grid */}
      <div style={{ padding:'16px', maxWidth:960, margin:'0 auto' }}>
        {filtered.length === 0 ? (
          <div style={{ textAlign:'center', padding:'60px 20px', color:'#9ca3af' }}>
            <div style={{ fontSize:48, marginBottom:12 }}>📷</div>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:6 }}>
              {docs.length === 0 ? 'אין תמונות עדיין' : 'לא נמצאו תמונות'}
            </div>
            <div style={{ fontSize:13 }}>
              {docs.length === 0 ? 'לחץ על "+ צלם / העלה" להוספת תיעוד' : 'נסה לשנות את הפילטר'}
            </div>
            {docs.length === 0 && (
              <button onClick={() => setShowModal(true)} style={{
                marginTop:20, padding:'11px 24px', borderRadius:8, border:'none',
                background:'#1a2c4a', color:'#fff', fontSize:14, fontWeight:700,
                cursor:'pointer', fontFamily:'inherit',
              }}>+ צלם / העלה תמונה ראשונה</button>
            )}
          </div>
        ) : (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))', gap:12 }}>
            {filtered.map(doc => (
              <PhotoCard key={doc.id} doc={doc} onDelete={deleteDoc}/>
            ))}
          </div>
        )}
      </div>

      {showModal && (
        <AddPhotoModal
          projectId={projectId}
          onClose={() => setShowModal(false)}
          onAdded={() => setDocs(loadDocs(projectId))}
        />
      )}
    </div>
  );
};

window.SiteDocScreen = SiteDocScreen;
})();
