/**
 * CRM — Customers Module
 * CustomersScreen: רשימת לקוחות + פרטי לקוח + טופס
 * cloudSave key: 'crm_customers'
 */
(function () {

// ── Data helpers — משתמש ב-SyncStore (מקור אמת יחיד) ─────────────────────────
function genId() {
  return 'cust_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
}

function loadCustomers() {
  return window.SyncStore ? window.SyncStore.getCustomers() : [];
}

function saveCustomers(list) {
  if (window.SyncStore) window.SyncStore.saveCustomers(list);
}

// ── Shared form primitives (מחוץ לקומפוננטה — למנוע re-mount בכל render) ──────
const crmInpStyle = {
  width: '100%', padding: '10px 12px', borderRadius: 8,
  border: '1.5px solid var(--ybp-border,#e5e7eb)',
  fontSize: 15, fontFamily: 'Assistant, sans-serif',
  background: 'var(--ybp-input-bg,#fff)',
  color: 'var(--ybp-ink,#111827)',
  outline: 'none', boxSizing: 'border-box', direction: 'rtl',
};

const CrmField = ({ label, required, error, children }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
    <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3 }}>
      {label}{required && <span style={{ color: '#dc2626', marginRight: 3 }}>*</span>}
    </label>
    {children}
    {error && <span style={{ fontSize: 11, color: '#dc2626' }}>{error}</span>}
  </div>
);

// ── CustomerForm ──────────────────────────────────────────────────────────────
const CustomerForm = ({ initial, onSave, onCancel }) => {
  const [form, setForm] = React.useState({
    name: '',
    company: '',
    taxId: '',
    accountingPhone: '',
    accountingEmail: '',
    address: '',
    notes: '',
    active: true,
    ...(initial || {}),
  });
  const [errors, setErrors] = React.useState({});

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'שדה חובה';
    if (!form.company.trim()) e.company = 'שדה חובה';
    if (form.taxId && !/^\d{9}$/.test(form.taxId.replace(/[-\s]/g, ''))) e.taxId = 'ח.פ חייב להיות 9 ספרות';
    if (form.accountingEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.accountingEmail)) e.accountingEmail = 'פורמט מייל לא תקין';
    if (form.accountingPhone && !/^[\d\-+\s]{7,15}$/.test(form.accountingPhone)) e.accountingPhone = 'טלפון לא תקין';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = () => {
    if (!validate()) return;
    onSave(form);
  };

  return (
    <div style={{ fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{
        padding: '16px 20px', borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onCancel} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, display: 'flex' }}>
          <Icon name="chevronR" size={22} color="var(--ybp-ink-soft,#6b7280)" />
        </button>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
          {initial ? 'עריכת לקוח' : 'לקוח חדש'}
        </h2>
      </div>

      {/* Form body */}
      <div style={{ padding: '20px', display: 'flex', flexDirection: 'column', gap: 16, overflowY: 'auto', maxHeight: 'calc(100vh - 130px)' }}>
        <CrmField label="שם הלקוח" required error={errors.name}>
          <input style={{ ...crmInpStyle, borderColor: errors.name ? '#dc2626' : undefined }}
            value={form.name} onChange={e => set('name', e.target.value)}
            onBlur={() => { if (!form.name.trim()) setErrors(p => ({ ...p, name: 'שדה חובה' })); }}
            placeholder="ישראל ישראלי" />
        </CrmField>

        <CrmField label="שם חברה לחשבונית" required error={errors.company}>
          <input style={{ ...crmInpStyle, borderColor: errors.company ? '#dc2626' : undefined }}
            value={form.company} onChange={e => set('company', e.target.value)}
            placeholder='ישראלי בע"מ' />
        </CrmField>

        <CrmField label="ח.פ / ע.מ" error={errors.taxId}>
          <input style={{ ...crmInpStyle, borderColor: errors.taxId ? '#dc2626' : undefined, direction: 'ltr', textAlign: 'right' }}
            value={form.taxId} onChange={e => set('taxId', e.target.value)}
            placeholder="514000000" maxLength={9} />
        </CrmField>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <CrmField label="טלפון הנהלת חשבונות" error={errors.accountingPhone}>
            <input style={{ ...crmInpStyle, direction: 'ltr', textAlign: 'right', borderColor: errors.accountingPhone ? '#dc2626' : undefined }}
              value={form.accountingPhone} onChange={e => set('accountingPhone', e.target.value)}
              placeholder="03-000-0000" />
          </CrmField>
          <CrmField label='דוא"ל הנהלת חשבונות' error={errors.accountingEmail}>
            <input style={{ ...crmInpStyle, direction: 'ltr', textAlign: 'right', borderColor: errors.accountingEmail ? '#dc2626' : undefined }}
              value={form.accountingEmail} onChange={e => set('accountingEmail', e.target.value)}
              placeholder="accounting@co.il" />
          </CrmField>
        </div>

        <CrmField label="כתובת משרדים">
          <input style={crmInpStyle} value={form.address} onChange={e => set('address', e.target.value)}
            placeholder="רחוב, עיר" />
        </CrmField>

        <CrmField label="הערות">
          <textarea style={{ ...crmInpStyle, minHeight: 80, resize: 'vertical' }}
            value={form.notes} onChange={e => set('notes', e.target.value)}
            placeholder="מידע נוסף..." />
        </CrmField>

        {/* Active toggle */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>
            <div onClick={() => set('active', !form.active)} style={{
              width: 40, height: 22, borderRadius: 11,
              background: form.active ? '#1a2c4a' : '#d1d5db',
              position: 'relative', cursor: 'pointer', transition: 'background 0.2s',
              flexShrink: 0,
            }}>
              <div style={{
                position: 'absolute', top: 3, right: form.active ? 3 : undefined, left: form.active ? undefined : 3,
                width: 16, height: 16, borderRadius: '50%', background: '#fff',
                transition: 'all 0.2s',
              }} />
            </div>
            לקוח פעיל
          </label>
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', gap: 10, paddingTop: 8 }}>
          <button onClick={handleSubmit} style={{
            flex: 1, padding: '13px', borderRadius: 9,
            background: '#1a2c4a', color: '#fff',
            border: 'none', fontSize: 15, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>
            {initial ? 'שמור שינויים' : 'הוסף לקוח'}
          </button>
          <button onClick={onCancel} style={{
            padding: '13px 20px', borderRadius: 9,
            background: 'var(--ybp-row-hover,#f3f4f6)',
            border: '1px solid var(--ybp-border,#e5e7eb)',
            color: 'var(--ybp-ink,#111827)',
            fontSize: 15, fontWeight: 600, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>ביטול</button>
        </div>
      </div>
    </div>
  );
};

// ── CustomerDetail ────────────────────────────────────────────────────────────
const CustomerDetail = ({ customerId, onBack, onEdit }) => {
  const customers = loadCustomers();
  const cust = customers.find(c => c.id === customerId);

  if (!cust) return (
    <div style={{ padding: 40, textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', fontFamily: 'Assistant, sans-serif' }}>
      לקוח לא נמצא
    </div>
  );

  const projects = (window.YBP_DATA || { projects: [] }).projects.filter(p => (cust.projectIds || []).includes(p.id));

  const Row = ({ label, value, isLink, href }) => value ? (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3, padding: '12px 0', borderBottom: '1px solid var(--ybp-border,#e5e7eb)' }}>
      <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)', letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</span>
      {isLink
        ? <a href={href} style={{ fontSize: 14, color: '#1a2c4a', fontWeight: 500 }}>{value}</a>
        : <span style={{ fontSize: 14, color: 'var(--ybp-ink,#111827)', fontWeight: 500 }}>{value}</span>
      }
    </div>
  ) : null;

  return (
    <div style={{ fontFamily: 'Assistant, sans-serif', direction: 'rtl', minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)' }}>
      {/* Header */}
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        padding: '16px 20px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4, display: 'flex' }}>
            <Icon name="chevronR" size={22} color="var(--ybp-ink-soft,#6b7280)" />
          </button>
          <div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{cust.name}</h2>
            <div style={{ fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)' }}>{cust.company}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {cust.accountingPhone && (
            <a href={`tel:${cust.accountingPhone}`} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '8px 14px', borderRadius: 8,
              background: '#f0fdf4', color: '#16a34a',
              border: '1px solid #bbf7d0',
              fontSize: 13, fontWeight: 600, textDecoration: 'none',
            }}>
              <Icon name="phone" size={15} color="#16a34a" /> שיחה
            </a>
          )}
          <button onClick={onEdit} style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '8px 14px', borderRadius: 8,
            background: '#1a2c4a', color: '#fff',
            border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>
            <Icon name="edit" size={15} color="#fff" /> ערוך
          </button>
        </div>
      </div>

      <div style={{ padding: 16, maxWidth: 560, margin: '0 auto' }}>
        {/* Status badge */}
        <div style={{ marginBottom: 16 }}>
          <span style={{
            padding: '4px 12px', borderRadius: 99, fontSize: 12, fontWeight: 600,
            background: cust.active ? '#f0fdf4' : '#f9fafb',
            color: cust.active ? '#16a34a' : '#6b7280',
          }}>
            {cust.active ? '● פעיל' : '○ לא פעיל'}
          </span>
        </div>

        {/* Details card */}
        <div style={{
          background: 'var(--ybp-panel,#fff)',
          borderRadius: 12, padding: '0 20px',
          border: '1px solid var(--ybp-border,#e5e7eb)',
          marginBottom: 16,
        }}>
          <Row label="שם חברה לחשבונית" value={cust.company} />
          <Row label="ח.פ / ע.מ" value={cust.taxId} />
          <Row label="טלפון הנהלת חשבונות" value={cust.accountingPhone} isLink href={`tel:${cust.accountingPhone}`} />
          <Row label='דוא"ל הנהלת חשבונות' value={cust.accountingEmail} isLink href={`mailto:${cust.accountingEmail}`} />
          <Row label="כתובת" value={cust.address} />
          {cust.notes && <Row label="הערות" value={cust.notes} />}
        </div>

        {/* Projects */}
        {projects.length > 0 && (
          <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)', marginBottom: 16 }}>
            <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
              פרויקטים מקושרים ({projects.length})
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {projects.map(p => (
                <div key={p.id} style={{
                  padding: '10px 14px', borderRadius: 8,
                  background: 'var(--ybp-row-hover,#f6f7f9)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                }}>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{p.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>{p.location}</div>
                  </div>
                  <span style={{
                    padding: '3px 8px', borderRadius: 6, fontSize: 11, fontWeight: 600,
                    background: '#eff6ff', color: '#2563eb',
                  }}>{p.status}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Created */}
        <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#9ca3af)', textAlign: 'center', marginTop: 8 }}>
          נוסף בתאריך {cust.createdAt || '—'}
        </div>
      </div>
    </div>
  );
};

// ── CustomersScreen (main) ────────────────────────────────────────────────────
const CustomersScreen = ({ onBack }) => {
  const [customers, setCustomers] = React.useState(loadCustomers);
  const [view, setView] = React.useState('list'); // list | detail | form
  const [selectedId, setSelectedId] = React.useState(null);
  const [editCustomer, setEditCustomer] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [filterActive, setFilterActive] = React.useState('all'); // all | active | inactive
  const [confirmDelete, setConfirmDelete] = React.useState(null);

  const filtered = customers.filter(c => {
    const matchSearch = !search ||
      c.name.includes(search) ||
      c.company.includes(search) ||
      (c.taxId || '').includes(search);
    const matchActive =
      filterActive === 'all' ? true :
      filterActive === 'active' ? c.active :
      !c.active;
    return matchSearch && matchActive;
  });

  const persist = (list) => { setCustomers(list); saveCustomers(list); };

  const handleSave = (form) => {
    if (editCustomer && editCustomer.id) {
      // update
      const updated = customers.map(c => c.id === editCustomer.id ? { ...c, ...form } : c);
      persist(updated);
      window.toastSuccess && window.toastSuccess('פרטי לקוח עודכנו');
    } else {
      // create
      const newC = { ...form, id: genId(), createdAt: new Date().toLocaleDateString('he-IL'), projectIds: [] };
      persist([newC, ...customers]);
      window.toastSuccess && window.toastSuccess('לקוח חדש נוסף');
    }
    setView('list');
    setEditCustomer(null);
  };

  const handleDelete = (id) => {
    persist(customers.filter(c => c.id !== id));
    window.toastSuccess && window.toastSuccess('הלקוח נמחק');
    setView('list');
    setConfirmDelete(null);
  };

  // ── View: form ──────────────────────────────────────────────────────────────
  if (view === 'form') {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)' }}>
        <CustomerForm
          initial={editCustomer}
          onSave={handleSave}
          onCancel={() => { setView(editCustomer ? 'detail' : 'list'); setEditCustomer(null); }}
        />
      </div>
    );
  }

  // ── View: detail ────────────────────────────────────────────────────────────
  if (view === 'detail' && selectedId) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)' }}>
        <CustomerDetail
          customerId={selectedId}
          onBack={() => setView('list')}
          onEdit={() => {
            const c = customers.find(x => x.id === selectedId);
            setEditCustomer(c);
            setView('form');
          }}
        />
        {/* Delete button */}
        <div style={{ padding: '0 16px 32px', maxWidth: 560, margin: '0 auto' }}>
          <button onClick={() => setConfirmDelete(selectedId)} style={{
            width: '100%', padding: 13, borderRadius: 9,
            background: '#fef2f2', color: '#dc2626',
            border: '1px solid #fecaca', fontSize: 14, fontWeight: 600, cursor: 'pointer',
          }}>
            מחק לקוח
          </button>
        </div>
        {confirmDelete && (
          <ConfirmDialog
            isOpen
            title="מחק לקוח?"
            description="הפעולה אינה הפיכה. כל הנתונים של הלקוח יימחקו."
            confirmLabel="מחק"
            confirmVariant="danger"
            onConfirm={() => handleDelete(confirmDelete)}
            onCancel={() => setConfirmDelete(null)}
          />
        )}
      </div>
    );
  }

  // ── View: list ──────────────────────────────────────────────────────────────
  return (
    <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        background: '#1a2c4a', color: '#fff',
        padding: '14px 20px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        position: 'sticky', top: 0, zIndex: 50,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff', cursor: 'pointer', padding: '5px 10px', borderRadius: 6, fontFamily: 'inherit', fontSize: 13 }}>
            ← חזרה
          </button>
          <div>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#fff' }}>לקוחות</h1>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>{customers.filter(c => c.active).length} פעילים</div>
          </div>
        </div>
        <button onClick={() => { setEditCustomer(null); setView('form'); }} style={{
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '9px 16px', borderRadius: 8,
          background: 'rgba(255,255,255,0.15)', color: '#fff',
          border: '1px solid rgba(255,255,255,0.25)', fontSize: 14, fontWeight: 600, cursor: 'pointer',
        }}>
          <Icon name="plus" size={16} color="#fff" /> לקוח חדש
        </button>
      </div>

      {/* Search + filter */}
      <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ position: 'relative' }}>
          <Icon name="search" size={16} color="var(--ybp-ink-faint,#9ca3af)"
            style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
          <input
            value={search} onChange={e => setSearch(e.target.value)}
            placeholder="חיפוש לפי שם, חברה, ח.פ..."
            style={{
              width: '100%', padding: '10px 40px 10px 12px',
              borderRadius: 9, border: '1px solid var(--ybp-border,#e5e7eb)',
              fontSize: 14, fontFamily: 'Assistant, sans-serif',
              background: 'var(--ybp-panel,#fff)',
              color: 'var(--ybp-ink,#111827)',
              outline: 'none', boxSizing: 'border-box', direction: 'rtl',
            }}
          />
        </div>
        {/* Filter chips */}
        <div style={{ display: 'flex', gap: 8 }}>
          {[['all', 'הכל'], ['active', 'פעילים'], ['inactive', 'לא פעילים']].map(([k, label]) => (
            <button key={k} onClick={() => setFilterActive(k)} style={{
              padding: '6px 14px', borderRadius: 99,
              background: filterActive === k ? '#1a2c4a' : 'var(--ybp-panel,#fff)',
              color: filterActive === k ? '#fff' : 'var(--ybp-ink-soft,#374151)',
              border: '1px solid ' + (filterActive === k ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'),
              fontSize: 12, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'Assistant, sans-serif',
            }}>{label}</button>
          ))}
        </div>
      </div>

      {/* List */}
      <div style={{ padding: '0 16px 32px' }}>
        {filtered.length === 0 ? (
          <EmptyState
            icon="users"
            title={search ? 'לא נמצאו לקוחות' : 'אין לקוחות עדיין'}
            description={search ? 'נסה חיפוש אחר' : 'התחל לבנות את ה-CRM שלך'}
            primaryAction={search ? { label: 'נקה חיפוש', onClick: () => setSearch('') } : { label: '+ לקוח חדש', onClick: () => setView('form') }}
          />
        ) : (
          filtered.map(c => (
            <div key={c.id}
              onClick={() => { setSelectedId(c.id); setView('detail'); }}
              style={{
                background: 'var(--ybp-panel,#fff)',
                borderRadius: 10, padding: '14px 16px',
                marginBottom: 10,
                border: '1px solid var(--ybp-border,#e5e7eb)',
                cursor: 'pointer', display: 'flex', gap: 14, alignItems: 'flex-start',
                transition: 'box-shadow 0.15s',
              }}
              onMouseEnter={e => e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'}
              onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
            >
              {/* Avatar */}
              <div style={{
                width: 44, height: 44, borderRadius: 10,
                background: '#eef2ff', color: '#1a2c4a',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 17, fontWeight: 700, flexShrink: 0,
              }}>
                {c.name.charAt(0)}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ybp-ink,#111827)' }}>{c.name}</div>
                  <span style={{
                    padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600, flexShrink: 0,
                    background: c.active ? '#f0fdf4' : '#f9fafb',
                    color: c.active ? '#16a34a' : '#6b7280',
                  }}>{c.active ? 'פעיל' : 'לא פעיל'}</span>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ybp-ink-soft,#374151)', marginTop: 2 }}>{c.company}</div>
                {c.accountingPhone && (
                  <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Icon name="phone" size={12} color="var(--ybp-ink-faint,#9ca3af)" />
                    {c.accountingPhone}
                  </div>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

Object.assign(window, { CustomersScreen });
})();
