// Cost Codes (รหัสต้นทุน) page — hierarchical cost code library with M/L/E pattern
// Inspired by BuildPM Pro reference layout

function CostCodesPage({ lang }) {
  // Load from localStorage if customized; else use master template
  const [data, setData] = useState(() => {
    try {
      const saved = localStorage.getItem('syk-cost-codes');
      if (saved) return JSON.parse(saved);
    } catch {}
    return window.MASTER_COST_CODES || [];
  });
  const [expanded, setExpanded] = useState({});  // { 'main-200': true, 'sub-203': true }
  const [filter, setFilter] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const toast = useToast();

  // Persist any change to localStorage
  useEffect(() => {
    localStorage.setItem('syk-cost-codes', JSON.stringify(data));
  }, [data]);

  // Toggle expand/collapse
  const toggle = (key) => setExpanded(prev => ({ ...prev, [key]: !prev[key] }));
  const expandAll = () => {
    const next = {};
    data.forEach(cat => {
      next['main-' + cat.code] = true;
      (cat.subs || []).forEach(sub => { next['sub-' + sub.code] = true; });
    });
    setExpanded(next);
  };
  const collapseAll = () => setExpanded({});

  // Stats
  const stats = useMemo(() => {
    let totalSubs = 0, totalItems = 0;
    for (const c of data) {
      totalSubs += (c.subs || []).length;
      for (const s of (c.subs || [])) totalItems += (s.items || []).length;
    }
    return { categories: data.length, subs: totalSubs, items: totalItems };
  }, [data]);

  // Filter
  const filtered = useMemo(() => {
    const q = filter.trim().toLowerCase();
    return data
      .filter(cat => categoryFilter === 'all' || cat.code === categoryFilter)
      .map(cat => {
        if (!q) return cat;
        const subs = (cat.subs || []).filter(sub => {
          if (sub.name.toLowerCase().includes(q) || sub.code.includes(q)) return true;
          return (sub.items || []).some(it =>
            it.name.toLowerCase().includes(q) || it.code.includes(q));
        }).map(sub => {
          if (sub.name.toLowerCase().includes(q) || sub.code.includes(q)) return sub;
          return { ...sub, items: (sub.items || []).filter(it =>
            it.name.toLowerCase().includes(q) || it.code.includes(q)) };
        });
        return { ...cat, subs };
      })
      .filter(cat => (cat.subs || []).length > 0);
  }, [data, filter, categoryFilter]);

  // ── Mutations ───────────────────────────────────────
  const updateCategory = (catIdx, patch) => setData(prev => {
    const next = [...prev];
    next[catIdx] = { ...next[catIdx], ...patch };
    return next;
  });
  const updateSub = (catIdx, subIdx, patch) => setData(prev => {
    const next = [...prev];
    const cat = { ...next[catIdx] };
    cat.subs = [...cat.subs];
    cat.subs[subIdx] = { ...cat.subs[subIdx], ...patch };
    next[catIdx] = cat;
    return next;
  });
  const updateItem = (catIdx, subIdx, itemIdx, patch) => setData(prev => {
    const next = [...prev];
    const cat = { ...next[catIdx] };
    cat.subs = [...cat.subs];
    const sub = { ...cat.subs[subIdx] };
    sub.items = [...sub.items];
    sub.items[itemIdx] = { ...sub.items[itemIdx], ...patch };
    cat.subs[subIdx] = sub;
    next[catIdx] = cat;
    return next;
  });
  const addItem = (catIdx, subIdx) => setData(prev => {
    const next = [...prev];
    const cat = { ...next[catIdx] };
    cat.subs = [...cat.subs];
    const sub = { ...cat.subs[subIdx] };
    const items = [...(sub.items || [])];
    const nextCode = String(items.length + 1).padStart(3, '0');
    items.push({ code: nextCode, name: '' });
    sub.items = items;
    cat.subs[subIdx] = sub;
    next[catIdx] = cat;
    return next;
  });
  const removeItem = (catIdx, subIdx, itemIdx) => setData(prev => {
    const next = [...prev];
    const cat = { ...next[catIdx] };
    cat.subs = [...cat.subs];
    const sub = { ...cat.subs[subIdx] };
    sub.items = sub.items.filter((_, i) => i !== itemIdx);
    cat.subs[subIdx] = sub;
    next[catIdx] = cat;
    return next;
  });
  const removeSub = (catIdx, subIdx) => {
    if (!confirm(lang === 'th' ? 'ลบหมวดย่อยนี้?' : 'Delete sub-category?')) return;
    setData(prev => {
      const next = [...prev];
      next[catIdx] = { ...next[catIdx], subs: next[catIdx].subs.filter((_, i) => i !== subIdx) };
      return next;
    });
  };
  const addSub = (catIdx) => {
    setData(prev => {
      const next = [...prev];
      const cat = { ...next[catIdx] };
      const subs = [...(cat.subs || [])];
      const baseCode = parseInt(cat.code);
      const nextCode = String(baseCode + subs.length + 1);
      subs.push({ code: nextCode, name: 'หมวดย่อยใหม่', items: [] });
      cat.subs = subs;
      next[catIdx] = cat;
      return next;
    });
  };
  const resetToMaster = () => {
    if (!confirm(lang === 'th' ? 'รีเซ็ตเป็น template มาตรฐาน? ข้อมูลที่แก้ไว้จะหายหมด' : 'Reset to master template?')) return;
    setData(window.MASTER_COST_CODES);
    toast(lang === 'th' ? 'รีเซ็ตเรียบร้อย' : 'Reset complete', 'success');
  };
  const exportJson = () => {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `cost-codes-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
    toast(lang === 'th' ? 'Export แล้ว' : 'Exported', 'success');
  };

  return (
    <div className="anim-fadein">
      <PageHeader
        title={lang === 'th' ? 'รหัสต้นทุน (Cost Code)' : 'Cost Code Library'}
        subtitle={lang === 'th'
          ? `${stats.categories} หมวด · ${stats.subs} หมวดย่อย · ${stats.items} รายการ — ใช้รหัส M (วัสดุ) / L (แรง) / E (เครื่องจักร)`
          : `${stats.categories} cats · ${stats.subs} subs · ${stats.items} items — M (Material) / L (Labor) / E (Equipment)`}
        actions={<>
          <button className="btn btn-sm" onClick={expandAll}><I.expand /> {lang === 'th' ? 'ขยายทั้งหมด' : 'Expand all'}</button>
          <button className="btn btn-sm" onClick={collapseAll}><I.chev dir="down" /> {lang === 'th' ? 'หุบทั้งหมด' : 'Collapse all'}</button>
          <button className="btn btn-sm" onClick={exportJson}><I.download /> Export</button>
          <button className="btn btn-sm" onClick={resetToMaster} style={{ color: 'var(--rose)' }}><I.refresh /> {lang === 'th' ? 'รีเซ็ต' : 'Reset'}</button>
        </>}
      />

      {/* Filter bar */}
      <div className="card card-tight" style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ position: 'relative', flex: '0 1 320px' }}>
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-mute)' }}><I.search /></span>
          <input className="field" placeholder={lang === 'th' ? 'ค้นหา รหัส / รายการ...' : 'Search code / item...'}
            value={filter} onChange={(e) => setFilter(e.target.value)} style={{ paddingLeft: 36, height: 36 }} />
        </div>
        <select className="field" style={{ width: 220, height: 36, fontSize: 12 }}
          value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)}>
          <option value="all">{lang === 'th' ? 'ทุกหมวดงาน' : 'All categories'}</option>
          {data.map(c => (
            <option key={c.code} value={c.code}>{c.icon} {c.code} — {c.name}</option>
          ))}
        </select>
        <div style={{ flex: 1 }} />
        <span className="chip">{stats.items} {lang === 'th' ? 'รายการ' : 'items'}</span>
        <span className="chip info">{stats.subs} {lang === 'th' ? 'หมวดย่อย' : 'subs'}</span>
        <span className="chip success">{stats.categories} {lang === 'th' ? 'หมวด' : 'categories'}</span>
      </div>

      {/* Categories */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {filtered.map((cat, ci) => {
          const realCatIdx = data.findIndex(c => c.code === cat.code);
          const catKey = 'main-' + cat.code;
          const catExpanded = expanded[catKey];
          const subCount = (cat.subs || []).reduce((a, s) => a + (s.items?.length || 0), 0);

          return (
            <div key={cat.code} className="card" style={{ padding: 0, overflow: 'hidden' }}>
              {/* Category header */}
              <div onClick={() => toggle(catKey)} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px',
                background: 'linear-gradient(90deg, rgba(40,72,255,0.15), rgba(40,72,255,0.03))',
                borderBottom: catExpanded ? '1px solid var(--line)' : 'none',
                cursor: 'pointer',
              }}>
                <span style={{ fontSize: 18, transform: catExpanded ? 'rotate(0deg)' : 'rotate(-90deg)', transition: '.2s', display: 'inline-block', color: 'var(--syk-blue-soft)' }}>▼</span>
                <span style={{ fontSize: 26 }}>{cat.icon}</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 800, fontSize: 18, color: 'var(--syk-blue-soft)', minWidth: 50 }}>{cat.code}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>{cat.name}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{cat.name_en}</div>
                </div>
                <span className="chip">{(cat.subs || []).length} {lang === 'th' ? 'หมวดย่อย' : 'subs'}</span>
                <span className="chip info">{subCount} {lang === 'th' ? 'รายการ' : 'items'}</span>
              </div>

              {/* Sub-categories */}
              {catExpanded && (
                <div style={{ padding: '8px 14px 14px' }}>
                  {(cat.subs || []).map((sub, si) => {
                    const realSubIdx = data[realCatIdx].subs.findIndex(s => s.code === sub.code);
                    const subKey = 'sub-' + sub.code;
                    const subExpanded = expanded[subKey];
                    return (
                      <div key={sub.code} style={{
                        marginBottom: 10, border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden',
                        background: 'var(--glass)',
                      }}>
                        {/* Sub header */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: 'var(--glass-2)' }}>
                          <span onClick={() => toggle(subKey)} style={{ cursor: 'pointer', color: 'var(--ink-mute)', fontSize: 12, transform: subExpanded ? 'rotate(0deg)' : 'rotate(-90deg)', display: 'inline-block', transition: '.2s' }}>▼</span>
                          <input className="field" style={{ width: 72, height: 30, fontSize: 12, fontFamily: 'var(--font-mono)', padding: '0 8px', textAlign: 'center', fontWeight: 700, color: 'var(--syk-blue-soft)' }}
                            value={sub.code}
                            onChange={(e) => updateSub(realCatIdx, realSubIdx, { code: e.target.value })} />
                          <input className="field" style={{ flex: 1, height: 30, fontSize: 13, fontWeight: 600 }}
                            value={sub.name}
                            onChange={(e) => updateSub(realCatIdx, realSubIdx, { name: e.target.value })} />
                          <span className="chip">{(sub.items || []).length} {lang === 'th' ? 'รายการ' : 'items'}</span>
                          <button className="btn btn-sm btn-ghost" onClick={() => removeSub(realCatIdx, realSubIdx)} style={{ color: 'var(--rose)', padding: '0 8px' }}><I.trash /></button>
                        </div>

                        {/* Items */}
                        {subExpanded && (
                          <div style={{ padding: '6px 12px 10px' }}>
                            <div style={{ display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 8, padding: '6px 4px', fontSize: 10, color: 'var(--ink-mute)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600 }}>
                              <div>{lang === 'th' ? 'รหัส' : 'Code'}</div>
                              <div>{lang === 'th' ? 'รายละเอียด' : 'Description'}</div>
                              <div style={{ textAlign: 'right' }}>{lang === 'th' ? 'รหัสที่ใช้ (M/L/E)' : 'Codes'}</div>
                            </div>
                            {(sub.items || []).map((item, ii) => (
                              <ItemRow key={item.code + ii}
                                catCode={cat.code} subCode={sub.code} item={item}
                                onUpdate={(patch) => updateItem(realCatIdx, realSubIdx, ii, patch)}
                                onRemove={() => removeItem(realCatIdx, realSubIdx, ii)} />
                            ))}
                            <button onClick={() => addItem(realCatIdx, realSubIdx)}
                              style={{
                                width: '100%', padding: '8px', marginTop: 4,
                                background: 'transparent', border: '1px dashed var(--line-strong)', borderRadius: 8,
                                color: 'var(--ink-mute)', cursor: 'pointer', fontSize: 12,
                                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                                transition: 'all .15s',
                              }}
                              onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--glass-2)'; e.currentTarget.style.color = 'var(--ink)'; }}
                              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-mute)'; }}>
                              <I.plus /> {lang === 'th' ? 'เพิ่มรายการ' : 'Add item'}
                            </button>
                          </div>
                        )}
                      </div>
                    );
                  })}
                  <button onClick={() => addSub(realCatIdx)}
                    className="btn btn-sm" style={{ width: '100%', justifyContent: 'center', marginTop: 6 }}>
                    <I.plus /> {lang === 'th' ? 'เพิ่มหมวดย่อย' : 'Add sub-category'}
                  </button>
                </div>
              )}
            </div>
          );
        })}

        {filtered.length === 0 && (
          <div className="card" style={{ textAlign: 'center', padding: 60, color: 'var(--ink-mute)' }}>
            <div style={{ fontSize: 36 }}>🔍</div>
            <div style={{ marginTop: 12 }}>{lang === 'th' ? 'ไม่พบผลการค้นหา' : 'No results'}</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Item row ──────────────────────────────────────────────
function ItemRow({ catCode, subCode, item, onUpdate, onRemove }) {
  const [local, setLocal] = useState({ code: item.code, name: item.name });
  useEffect(() => { setLocal({ code: item.code, name: item.name }); }, [item.code, item.name]);

  const mCode = `M-${catCode === '100' ? subCode : (subCode || catCode)}-${item.code}`;
  const lCode = `L-${catCode === '100' ? subCode : (subCode || catCode)}-${item.code}`;
  const eCode = `E-${catCode === '100' ? subCode : (subCode || catCode)}-${item.code}`;

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 8,
      padding: '6px 0', alignItems: 'center',
    }}>
      <input className="field" value={local.code}
        onChange={(e) => { setLocal({ ...local, code: e.target.value }); }}
        onBlur={() => onUpdate({ code: local.code })}
        style={{ height: 30, padding: '0 8px', fontSize: 11.5, fontFamily: 'var(--font-mono)', textAlign: 'center' }} />
      <input className="field" value={local.name}
        onChange={(e) => { setLocal({ ...local, name: e.target.value }); }}
        onBlur={() => onUpdate({ name: local.name })}
        placeholder="รายละเอียดรายการ"
        style={{ height: 30, padding: '0 10px', fontSize: 12 }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <CodeBadge code={mCode} color="#a78bfa" label="M" tooltip="Material" />
        <CodeBadge code={lCode} color="#f472b6" label="L" tooltip="Labor" />
        <CodeBadge code={eCode} color="#fbbf24" label="E" tooltip="Equipment" />
        <button onClick={onRemove}
          style={{ background: 'transparent', border: 0, color: 'var(--rose)', cursor: 'pointer', padding: '0 6px', opacity: 0.5, fontSize: 14 }}
          onMouseEnter={(e) => e.currentTarget.style.opacity = 1}
          onMouseLeave={(e) => e.currentTarget.style.opacity = 0.5}
          title="ลบ">×</button>
      </div>
    </div>
  );
}

function CodeBadge({ code, color, label, tooltip }) {
  const copy = () => {
    navigator.clipboard?.writeText(code);
  };
  return (
    <span onClick={copy} title={`${tooltip}: ${code} (คลิกเพื่อ copy)`}
      style={{
        padding: '3px 8px', borderRadius: 6,
        background: `${color}15`, border: `1px solid ${color}40`,
        color: color, fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)',
        cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap',
      }}>
      {code}
    </span>
  );
}

window.CostCodesPage = CostCodesPage;
