// Plans screen — תוכניות הפרויקט עם מבנה Google Drive
(function(){
const { useState, useRef } = React;

// Drive folder tree from blueprint.json (extracted)
const DRIVE_TREE = [
  {
    id: 'plans', name: 'תוכניות', icon: '📐', children: [
      { id: 'arch', name: 'אדריכל', icon: '🏛️', children: [
        { id: 'arch-haamada', name: 'העמדה' }, { id: 'arch-binui', name: 'בינוי' },
        { id: 'arch-rictuf', name: 'ריצוף' }, { id: 'arch-tkrot', name: 'תקרות' },
        { id: 'arch-gmarim', name: 'גמרים' }, { id: 'arch-hashmal', name: 'חשמל' },
        { id: 'arch-taora', name: 'תאורה' }, { id: 'arch-instl', name: 'אינסטלציה' },
        { id: 'arch-prisot', name: 'פריסות' }, { id: 'arch-chatachim', name: 'חתכים' },
        { id: 'arch-super', name: 'סופרפוזיציה' }, { id: 'arch-mifrat', name: 'מפרטים' },
        { id: 'arch-ngrut', name: 'נגרות' }, { id: 'arch-msgrot', name: 'מסגרות' },
        { id: 'arch-hadmiot', name: 'הדמיות' },
      ]},
      { id: 'kitchen', name: 'מטבח', icon: '🍽️', children: [
        { id: 'kit-haamada', name: 'העמדה' }, { id: 'kit-binui', name: 'בינוי' },
        { id: 'kit-rictuf', name: 'ריצוף' }, { id: 'kit-tkrot', name: 'תקרות' },
        { id: 'kit-gmarim', name: 'גמרים' }, { id: 'kit-hashmal', name: 'חשמל' },
        { id: 'kit-taora', name: 'תאורה' }, { id: 'kit-instl', name: 'אינסטלציה' },
        { id: 'kit-nirosta', name: 'חוברת נירוסטה' }, { id: 'kit-hadmiot', name: 'הדמיות' },
      ]},
      { id: 'complex', name: 'מתחם', icon: '🏗️', children: [
        { id: 'cmp-instl', name: 'אינסטלציה' }, { id: 'cmp-hashmal', name: 'חשמל' },
        { id: 'cmp-rshui', name: 'רישוי' }, { id: 'cmp-sviva', name: 'סביבה' },
        { id: 'cmp-kdihot', name: 'קידוחים' }, { id: 'cmp-knst', name: 'קונסטרוקציה' },
        { id: 'cmp-hazitot', name: 'חזיתות' },
      ]},
      { id: 'consult', name: 'יועצים', icon: '👔', children: [
        { id: 'con-hashmal', name: 'יועץ חשמל' }, { id: 'con-instl', name: 'יועץ אינסטלציה' },
        { id: 'con-mizug', name: 'יועץ מיזוג אוויר' }, { id: 'con-btihut', name: 'יועץ בטיחות' },
        { id: 'con-ngsht', name: 'יועץ נגישות' }, { id: 'con-mtn', name: 'יועץ מתח נמוך' },
        { id: 'con-taora', name: 'יועץ תאורה' }, { id: 'con-rshui', name: 'יועץ רישוי' },
        { id: 'con-kns', name: 'קונסטרוקטור' }, { id: 'con-acos', name: 'יועץ אקוסטיקה' },
      ]},
    ]
  },
];

// Flatten tree for quick lookup
function flattenTree(nodes, result = [], path = []) {
  for (const n of nodes) {
    const fullPath = [...path, n.name];
    result.push({ ...n, path: fullPath, depth: path.length });
    if (n.children) flattenTree(n.children, result, fullPath);
  }
  return result;
}
const ALL_FOLDERS = flattenTree(DRIVE_TREE);

// ============================================================
// Plans Screen
// ============================================================
const PlansScreen = ({ projectId, onBack }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId) || YBP_DATA.projects[0];
  const [plans, setPlans] = useState([
    // Demo plans already in the project
    { id: 'pl1', name: 'תוכנית אדריכל - העמדה Rev.3', folderId: 'arch-haamada', folderPath: ['תוכניות', 'אדריכל', 'העמדה'], file: null, addedAt: '2026-03-15', version: 'Rev.3', type: 'pdf' },
    { id: 'pl2', name: 'תוכנית ריצוף - כללי', folderId: 'arch-rictuf', folderPath: ['תוכניות', 'אדריכל', 'ריצוף'], file: null, addedAt: '2026-03-20', version: 'Rev.1', type: 'pdf' },
    { id: 'pl3', name: 'תוכנית חשמל - אדריכל', folderId: 'arch-hashmal', folderPath: ['תוכניות', 'אדריכל', 'חשמל'], file: null, addedAt: '2026-04-01', version: 'Rev.2', type: 'dwg' },
    { id: 'pl4', name: 'הדמיות מטבח - סופי', folderId: 'kit-hadmiot', folderPath: ['תוכניות', 'מטבח', 'הדמיות'], file: null, addedAt: '2026-04-10', version: 'Final', type: 'jpg' },
  ]);
  const [showUpload, setShowUpload] = useState(false);
  const [expandedFolders, setExpandedFolders] = useState({ plans: true, arch: true });
  const [activeFolder, setActiveFolder] = useState('all');

  const toggleFolder = (id) => setExpandedFolders(f => ({ ...f, [id]: !f[id] }));

  const filteredPlans = activeFolder === 'all'
    ? plans
    : plans.filter(p => p.folderId === activeFolder || p.folderPath.includes(ALL_FOLDERS.find(f => f.id === activeFolder)?.name));

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl' }}>
      {/* Header */}
      <header style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb', padding:'12px 20px',
        display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:10,
      }}>
        <button onClick={onBack} style={{
          background:'transparent', border:'none', cursor:'pointer', color:'#6b7280',
          display:'flex', alignItems:'center', gap:4, fontSize:14, padding:6, fontFamily:'inherit',
        }}>
          <Icon name="chevron" size={18}/> חזרה
        </button>
        <div style={{ width:1, height:24, background:'#e5e7eb' }}/>
        <span style={{ fontSize:15, fontWeight:700, color:'#1f2937' }}>תוכניות</span>
        <span style={{ fontSize:12, color:'#6b7280' }}>{project.name}</span>
        <div style={{ flex:1 }}/>
        <button onClick={() => setShowUpload(true)} style={{
          display:'flex', alignItems:'center', gap:6, padding:'8px 16px', borderRadius:6,
          background:'#1a2c4a', color:'#fff', border:'none', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
        }}>
          <Icon name="plus" size={14}/> העלאת תוכנית
        </button>
      </header>

      {/* Distribution banner */}
      {typeof PlansDistributionBanner !== 'undefined' && (
        <div style={{ padding: '12px 16px 0' }}>
          <PlansDistributionBanner projectId={projectId} />
        </div>
      )}

      <div style={{ display:'grid', gridTemplateColumns:'240px 1fr', minHeight:'calc(100vh - 57px)' }}>
        {/* Sidebar — folder tree */}
        <div style={{ background:'#fff', borderLeft:'1px solid #e5e7eb', padding:'12px 0', overflowY:'auto' }}>
          <div style={{ fontSize:11, fontWeight:700, color:'#9ca3af', padding:'4px 16px 8px', letterSpacing:0.5 }}>
            DRIVE · {project.name}
          </div>

          {/* "All" option */}
          <button
            onClick={() => setActiveFolder('all')}
            style={{
              width:'100%', padding:'8px 16px', background: activeFolder === 'all' ? '#eff6ff' : 'transparent',
              border:'none', textAlign:'right', fontSize:13, fontWeight: activeFolder === 'all' ? 700 : 400,
              color: activeFolder === 'all' ? '#1d4ed8' : '#374151', cursor:'pointer', fontFamily:'inherit',
            }}>
            📁 כל התוכניות ({plans.length})
          </button>

          <FolderTree
            nodes={DRIVE_TREE}
            expanded={expandedFolders}
            onToggle={toggleFolder}
            activeFolder={activeFolder}
            onSelect={setActiveFolder}
            plans={plans}
          />
        </div>

        {/* Main — plans grid */}
        <div style={{ padding:20 }}>
          {filteredPlans.length === 0 ? (
            <div style={{
              background:'#fff', border:'2px dashed #e5e7eb', borderRadius:12, padding:60,
              textAlign:'center', color:'#9ca3af',
            }}>
              <div style={{ fontSize:40, marginBottom:12 }}>📐</div>
              <div style={{ fontSize:15, fontWeight:600, marginBottom:6 }}>אין תוכניות בתיקייה זו</div>
              <div style={{ fontSize:13 }}>העלה תוכנית חדשה או בחר תיקייה אחרת</div>
            </div>
          ) : (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))', gap:14 }}>
              {filteredPlans.map(p => <PlanCard key={p.id} plan={p}/>)}
            </div>
          )}
        </div>
      </div>

      {showUpload && (
        <UploadPlanModal
          plans={plans}
          onSave={(newPlan) => {
            setPlans(ps => [...ps, { ...newPlan, id: `pl-${Date.now()}`, addedAt: new Date().toISOString().slice(0,10) }]);
            setShowUpload(false);
          }}
          onClose={() => setShowUpload(false)}
        />
      )}
    </div>
  );
};

// ============================================================
// Folder Tree component
// ============================================================
const FolderTree = ({ nodes, expanded, onToggle, activeFolder, onSelect, plans, depth = 0 }) => (
  <div>
    {nodes.map(node => {
      const isExp = expanded[node.id];
      const isActive = activeFolder === node.id;
      const count = plans.filter(p => p.folderId === node.id).length;
      return (
        <div key={node.id}>
          <button
            onClick={() => { if (node.children) onToggle(node.id); onSelect(node.id); }}
            style={{
              width:'100%', padding:`7px 16px 7px ${16 + depth * 12}px`,
              background: isActive ? '#eff6ff' : 'transparent', border:'none',
              textAlign:'right', fontSize:12.5,
              color: isActive ? '#1d4ed8' : '#374151',
              cursor:'pointer', fontFamily:'inherit',
              display:'flex', alignItems:'center', gap:6,
              fontWeight: isActive ? 700 : 400,
            }}
          >
            {node.children && (
              <span style={{ fontSize:10, color:'#9ca3af', transition:'transform 0.1s', display:'inline-block', transform: isExp ? 'rotate(90deg)' : 'none' }}>▶</span>
            )}
            <span>{node.icon || '📂'} {node.name}</span>
            {count > 0 && <span style={{ marginRight:'auto', fontSize:10, background:'#dbeafe', color:'#1d4ed8', padding:'1px 6px', borderRadius:8, fontWeight:700 }}>{count}</span>}
          </button>
          {node.children && isExp && (
            <FolderTree nodes={node.children} expanded={expanded} onToggle={onToggle} activeFolder={activeFolder} onSelect={onSelect} plans={plans} depth={depth + 1}/>
          )}
        </div>
      );
    })}
  </div>
);

// ============================================================
// Plan card
// ============================================================
const PlanCard = ({ plan }) => {
  const typeColors = { pdf: '#dc2626', dwg: '#0369a1', jpg: '#7c3aed', png: '#7c3aed', default: '#6b7280' };
  const color = typeColors[plan.type] || typeColors.default;
  return (
    <div style={{
      background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, overflow:'hidden',
      cursor:'pointer', transition:'all 0.15s',
    }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = '#1a2c4a'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.boxShadow = 'none'; }}>
      {/* Preview area */}
      <div style={{
        height:100, background:`linear-gradient(135deg, #f8fafc, #e2e8f0)`,
        display:'flex', alignItems:'center', justifyContent:'center', position:'relative',
      }}>
        <div style={{ fontSize:36 }}>📐</div>
        <div style={{
          position:'absolute', top:8, left:8, padding:'2px 7px', borderRadius:3,
          background: color, color:'#fff', fontSize:10, fontWeight:700, letterSpacing:0.5,
        }}>{plan.type?.toUpperCase()}</div>
      </div>
      <div style={{ padding:'10px 12px' }}>
        <div style={{ fontSize:12.5, fontWeight:600, color:'#1f2937', marginBottom:4, lineHeight:1.3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {plan.name}
        </div>
        <div style={{ fontSize:11, color:'#9ca3af', display:'flex', justifyContent:'space-between' }}>
          <span>{plan.version}</span>
          <span>{plan.addedAt}</span>
        </div>
        <div style={{ marginTop:6, fontSize:10.5, color:'#6b7280', background:'#f3f4f6', padding:'3px 6px', borderRadius:3 }}>
          {plan.folderPath.join(' › ')}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Upload modal — עם AI זיהוי תוכנית
// ============================================================
const AI_BADGE = (
  <span style={{
    fontSize:9, fontWeight:800, background:'#7c3aed', color:'#fff',
    padding:'1px 5px', borderRadius:3, marginRight:5, letterSpacing:0.3,
  }}>AI</span>
);

const UploadPlanModal = ({ onSave, onClose }) => {
  const { useRef: ur, useState: us } = React;
  const [name, setName] = us('');
  const [selectedFolder, setSelectedFolder] = us('');
  const [version, setVersion] = us('Rev.1');
  const [fileType, setFileType] = us('pdf');
  const [file, setFile] = us(null);
  const [aiState, setAiState] = us('idle'); // idle | analyzing | done | error
  const [aiFields, setAiFields] = us({}); // which fields were AI-filled
  const [preview, setPreview] = us(null); // base64 preview for images
  const fileRef = ur(null);
  const dropRef = ur(null);

  const folderOptions = ALL_FOLDERS.filter(f => !f.children);
  const isImage = file && ['jpg','jpeg','png','webp'].includes(file.name.split('.').pop()?.toLowerCase());

  // Load pdf.js and render first page to base64
  const renderPdfToBase64 = async (f) => {
    if (!window.pdfjsLib) {
      await new Promise((resolve, reject) => {
        const s = document.createElement('script');
        s.src = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.min.js';
        s.onload = resolve; s.onerror = reject;
        document.head.appendChild(s);
      });
      // fake worker — אין CORS issues
      window.pdfjsLib.GlobalWorkerOptions.workerSrc = '';
    }
    const arrayBuffer = await f.arrayBuffer();
    const pdf = await window.pdfjsLib.getDocument({ data: arrayBuffer, disableWorker: true }).promise;
    const page = await pdf.getPage(1);
    const scale = 2.5;
    const viewport = page.getViewport({ scale });
    const canvas = document.createElement('canvas');
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    await page.render({ canvasContext: canvas.getContext('2d'), viewport }).promise;
    return canvas.toDataURL('image/jpeg', 0.85);
  };

  const analyzeWithAI = async (f, base64) => {
    setAiState('analyzing');
    try {
      const ext = f.name.split('.').pop()?.toLowerCase();
      const mediaType = ext === 'png' ? 'image/png' : 'image/jpeg';
      const prompt = `זוהי תוכנית בנייה/אדריכלות. חלץ מהמסגרת (title block) את המידע הבא בפורמט JSON בלבד, ללא טקסט נוסף:
{
  "name": "שם התוכנית בעברית",
  "drawingNumber": "מספר גיליון",
  "revision": "גרסה כגון Rev.1 או B",
  "date": "תאריך YYYY-MM-DD",
  "discipline": "תחום: אדריכל/חשמל/אינסטלציה/מיזוג/קונסטרוקציה/מטבח/יועצים",
  "folderSuggestion": "אחת מ: arch-haamada|arch-binui|arch-rictuf|arch-tkrot|arch-gmarim|arch-hashmal|arch-taora|arch-instl|arch-prisot|arch-chatachim|arch-super|arch-mifrat|arch-ngrut|arch-msgrot|arch-hadmiot|kit-haamada|kit-binui|kit-nirosta|kit-hadmiot|cmp-instl|cmp-hashmal|cmp-rshui|cmp-knst|cmp-hazitot|con-hashmal|con-instl|con-mizug|con-btihut|con-ngsht|con-mtn|con-taora|con-rshui|con-kns|con-acos"
}
אם לא ניתן לחלץ שדה — השב null עבורו.`;

      const result = await window.claude.complete({
        messages: [{
          role: 'user',
          content: [
            { type: 'image', source: { type: 'base64', media_type: mediaType, data: base64.split(',')[1] } },
            { type: 'text', text: prompt }
          ]
        }]
      });

      // Parse JSON from result
      const jsonMatch = result.match(/\{[\s\S]*\}/);
      if (!jsonMatch) throw new Error('no JSON');
      const data = JSON.parse(jsonMatch[0]);

      const filled = {};
      if (data.name) { setName(data.name); filled.name = true; }
      if (data.revision) { setVersion(data.revision); filled.version = true; }
      if (data.folderSuggestion) {
        const folder = ALL_FOLDERS.find(f => f.id === data.folderSuggestion);
        if (folder) { setSelectedFolder(data.folderSuggestion); filled.folder = true; }
      }
      setAiFields(filled);
      setAiState('done');
    } catch(e) {
      setAiState('error');
    }
  };

  const handleFile = (f) => {
    if (!f) return;
    setFile(f);
    if (!name) setName(f.name.replace(/\.[^/.]+$/, ''));
    setFileType(f.name.split('.').pop()?.toLowerCase() || 'pdf');
    setAiFields({});
    setAiState('idle');

    const ext = f.name.split('.').pop()?.toLowerCase();
    if (['jpg','jpeg','png','webp'].includes(ext)) {
      const reader = new FileReader();
      reader.onload = e => {
        setPreview(e.target.result);
        analyzeWithAI(f, e.target.result);
      };
      reader.readAsDataURL(f);
    } else if (ext === 'pdf') {
      setAiState('analyzing');
      renderPdfToBase64(f).then(base64 => {
        setPreview(base64);
        analyzeWithAI(f, base64);
      }).catch(() => setAiState('error'));
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    const f = e.dataTransfer.files?.[0];
    if (f) handleFile(f);
    dropRef.current.style.borderColor = '#e5e7eb';
  };

  // PLACEHOLDER_UPLOAD_PLAN — תרחיש Make עדיין לא נוצר
  const MAKE_PLAN_WEBHOOK = 'https://hook.eu2.make.com/cwhco2m6u2m48ey692n7n7wagoz8cg0i';
  const MAKE_SK = '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';

  const handleSubmit = async () => {
    if (!name || !selectedFolder) return;
    const folder = ALL_FOLDERS.find(f => f.id === selectedFolder);
    const pmName = ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '') || 'מנהל';
    const projectObj = YBP_DATA.projects.find(p => p.id === projectId) || {};
    const folderPath = folder?.path?.join(' / ') || selectedFolder;
    const drivePath = `2026 / ${pmName} / ${projectObj.name || projectId} / תוכניות / ${folderPath}`;

    // שלח ל-Make → Drive
    if (file) {
      const date = new Date().toISOString().slice(0, 10);
      try {
        const blobToBase64 = (blob) => new Promise((res, rej) => {
          const r = new FileReader(); r.onload = () => res(r.result.split(',')[1]); r.onerror = rej; r.readAsDataURL(blob);
        });
        const fileBase64 = await blobToBase64(file);
        await fetch(MAKE_PLAN_WEBHOOK, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            _sk: MAKE_SK,
            manager: pmName,
            project: projectObj.name || projectId,
            type_name: `תוכנית — ${name}`,
            date,
            format: fileType === 'pdf' ? 'pdf' : 'html',
            pdf: fileBase64,
          }),
        });
      } catch {
        console.log('[Drive] plan upload failed — drivePath:', drivePath);
      }
    }

    onSave({ name, folderId: selectedFolder, folderPath: folder?.path || [], version, type: fileType, file, drivePath });
  };

  const inp = {
    width:'100%', padding:'9px 12px', borderRadius:6, border:'1px solid #e5e7eb',
    fontSize:13, fontFamily:'Assistant, sans-serif', direction:'rtl', boxSizing:'border-box',
  };

  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.4)', zIndex:100 }}/>
      <div style={{
        position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)',
        background:'#fff', borderRadius:12, width:'min(540px, 95vw)', maxHeight:'90vh', overflowY:'auto',
        zIndex:101, boxShadow:'0 20px 60px rgba(0,0,0,0.2)', fontFamily:'Assistant, sans-serif', direction:'rtl',
      }}>
        <div style={{ padding:'18px 22px', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>העלאת תוכנית חדשה</h3>
            <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>גרור תמונה — AI יזהה ויש לים את הפרטים אוטומטית</div>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', fontSize:20, cursor:'pointer', color:'#6b7280' }}>×</button>
        </div>

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

          {/* Drop zone */}
          <div
            ref={dropRef}
            onClick={() => fileRef.current?.click()}
            onDragOver={e => { e.preventDefault(); dropRef.current.style.borderColor = '#7c3aed'; }}
            onDragLeave={() => { dropRef.current.style.borderColor = file ? '#10b981' : '#e5e7eb'; }}
            onDrop={handleDrop}
            style={{
              border: file ? '2px solid #10b981' : '2px dashed #e5e7eb',
              borderRadius:10, padding:'20px 16px', textAlign:'center', cursor:'pointer',
              background: file ? '#f0fdf4' : '#fafafa', transition:'all 0.15s',
              display:'flex', alignItems:'center', gap:16,
            }}
          >
            {preview && (
              <img src={preview} alt="preview" style={{ width:80, height:60, objectFit:'cover', borderRadius:6, border:'1px solid #e5e7eb', flexShrink:0 }}/>
            )}
            <div style={{ flex:1, textAlign: preview ? 'right' : 'center' }}>
              {file ? (
                <>
                  <div style={{ fontSize:13, fontWeight:600, color:'#059669' }}>{file.name}</div>
                  <div style={{ fontSize:11, color:'#6b7280', marginTop:2 }}>{(file.size / 1024).toFixed(0)} KB</div>
                  {aiState === 'analyzing' && (
                    <div style={{ marginTop:6, fontSize:12, color:'#7c3aed', fontWeight:600, display:'flex', alignItems:'center', gap:6, justifyContent: preview ? 'flex-start' : 'center' }}>
                      <span style={{ display:'inline-block', animation:'spin 1s linear infinite', fontSize:14 }}>⟳</span>
                      מנתח תוכנית עם AI...
                    </div>
                  )}
                  {aiState === 'done' && (
                    <div style={{ marginTop:6, fontSize:12, color:'#7c3aed', fontWeight:600 }}>✓ AI זיהה {Object.keys(aiFields).length} שדות</div>
                  )}
                  {aiState === 'error' && (
                    <div style={{ marginTop:6, fontSize:11, color:'#f59e0b' }}>⚠️ לא ניתן לזהות — מלא ידנית</div>
                  )}
                </>
              ) : (
                <>
                  <div style={{ fontSize:32, marginBottom:8 }}>📐</div>
                  <div style={{ fontSize:13, fontWeight:600, color:'#374151' }}>גרור תוכנית לכאן או לחץ להעלאה</div>
                  <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>PDF / JPG / PNG → זיהוי AI אוטומטי · DWG, DXF → ידני</div>
                </>
              )}
            </div>
            <input ref={fileRef} type="file" accept=".pdf,.dwg,.dxf,.jpg,.jpeg,.png,.webp"
              onChange={e => handleFile(e.target.files?.[0])} style={{ display:'none' }}/>
          </div>

          {/* AI analyzing overlay */}
          {aiState === 'analyzing' && (
            <div style={{ background:'#faf5ff', border:'1px solid #e9d5ff', borderRadius:8, padding:'12px 14px', display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:32, height:32, borderRadius:16, background:'#7c3aed', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, flexShrink:0 }}>AI</div>
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'#6d28d9' }}>קורא את מסגרת הכותרת...</div>
                <div style={{ fontSize:11, color:'#8b5cf6' }}>מחלץ שם, גרסה, תחום ותיקייה מומלצת</div>
              </div>
            </div>
          )}

          {/* Name */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', marginBottom:5, display:'flex', alignItems:'center' }}>
              {aiFields.name && AI_BADGE}שם התוכנית *
            </label>
            <input value={name} onChange={e => setName(e.target.value)}
              placeholder="תוכנית אדריכל - העמדה"
              style={{ ...inp, border: aiFields.name ? '1px solid #7c3aed' : '1px solid #e5e7eb', background: aiFields.name ? '#faf5ff' : '#fff' }}/>
          </div>

          {/* Folder */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', marginBottom:5, display:'flex', alignItems:'center' }}>
              {aiFields.folder && AI_BADGE}שיוך לתיקייה בדרייב *
            </label>
            <select value={selectedFolder} onChange={e => setSelectedFolder(e.target.value)}
              style={{ ...inp, cursor:'pointer', border: aiFields.folder ? '1px solid #7c3aed' : '1px solid #e5e7eb', background: aiFields.folder ? '#faf5ff' : '#fff' }}>
              <option value="">— בחר תיקייה —</option>
              {folderOptions.map(f => (
                <option key={f.id} value={f.id}>{f.path.join(' › ')}</option>
              ))}
            </select>
          </div>

          {/* Version */}
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', marginBottom:5, display:'flex', alignItems:'center' }}>
              {aiFields.version && AI_BADGE}גרסה
            </label>
            <input value={version} onChange={e => setVersion(e.target.value)}
              placeholder="Rev.1"
              style={{ ...inp, width:'auto', maxWidth:140, border: aiFields.version ? '1px solid #7c3aed' : '1px solid #e5e7eb', background: aiFields.version ? '#faf5ff' : '#fff' }}/>
          </div>

          {Object.keys(aiFields).length > 0 && (
            <div style={{ fontSize:11, color:'#6b7280', background:'#f9fafb', padding:'8px 12px', borderRadius:6, border:'1px solid #f3f4f6' }}>
              💡 שדות עם תג <b style={{ color:'#7c3aed' }}>AI</b> זוהו אוטומטית — בדוק ואשר לפני שמירה
            </div>
          )}
        </div>

        <div style={{ padding:'14px 22px', borderTop:'1px solid #e5e7eb', display:'flex', gap:10 }}>
          <button
            onClick={handleSubmit}
            disabled={!name || !selectedFolder || aiState === 'analyzing'}
            style={{
              padding:'9px 20px', borderRadius:6, border:'none',
              background: (!name || !selectedFolder || aiState === 'analyzing') ? '#e5e7eb' : '#1a2c4a',
              color: (!name || !selectedFolder || aiState === 'analyzing') ? '#9ca3af' : '#fff',
              fontSize:13, fontWeight:700, cursor: (!name || !selectedFolder || aiState === 'analyzing') ? 'not-allowed' : 'pointer', fontFamily:'inherit',
            }}
          >{file ? 'העלה ושייך לדרייב' : 'שמור ללא קובץ'}</button>
          <button onClick={onClose} style={{ padding:'9px 16px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', color:'#6b7280', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>ביטול</button>
        </div>
      </div>
      <style>{`@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }`}</style>
    </>
  );
};

window.PlansScreen = PlansScreen;
})();
