// Documents view, POs & Quotes, Login, Supplier Registration

const DocumentsPage = ({ company }) => {
  const { DOCUMENTS, SUPPLIERS } = window.SaifData;
  const [sort, setSort] = React.useState('expires');
  const [filter, setFilter] = React.useState('all');

  let list = DOCUMENTS.map(d => {
    const supplier = SUPPLIERS.find(s => s.id === d.supplierId);
    return { ...d, supplier };
  });
  if (company !== 'all') list = list.filter(d => d.supplier && d.supplier.companies.includes(company));
  if (filter !== 'all') list = list.filter(d => d.status === filter);
  list = [...list].sort((a, b) => sort === 'expires' ? new Date(a.expires) - new Date(b.expires) : a.fileName.localeCompare(b.fileName));

  const counts = {
    red: DOCUMENTS.filter(d => d.status === 'red').length,
    amber: DOCUMENTS.filter(d => d.status === 'amber').length,
    green: DOCUMENTS.filter(d => d.status === 'green').length,
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Documents</h1>
          <p className="page-subtitle">All supplier documents across the group · {DOCUMENTS.length} total</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="filter" size={14}/> Filters</button>
          <button className="btn"><Icon name="download" size={14}/> Export</button>
          <button className="btn btn-primary"><Icon name="bell" size={14}/> Send renewal notices</button>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi" style={{ borderColor: 'var(--red-soft)' }}>
          <div className="kpi-spark"><span className="badge-dot" style={{ background: 'var(--red)', width: 9, height: 9 }}></span></div>
          <div className="kpi-label">Expired or expiring ≤7d</div>
          <div className="kpi-value" style={{ color: 'var(--red)' }}>{counts.red}</div>
          <div className="kpi-meta">Immediate action required</div>
        </div>
        <div className="kpi" style={{ borderColor: 'var(--amber-soft)' }}>
          <div className="kpi-spark"><span className="badge-dot" style={{ background: 'var(--amber)', width: 9, height: 9 }}></span></div>
          <div className="kpi-label">Expiring in 30 days</div>
          <div className="kpi-value" style={{ color: 'oklch(0.55 0.13 75)' }}>{counts.amber}</div>
          <div className="kpi-meta">Send 30-day notices</div>
        </div>
        <div className="kpi">
          <div className="kpi-spark"><span className="badge-dot" style={{ background: 'var(--green)', width: 9, height: 9 }}></span></div>
          <div className="kpi-label">Valid</div>
          <div className="kpi-value" style={{ color: 'var(--green)' }}>{counts.green}</div>
          <div className="kpi-meta">No action needed</div>
        </div>
        <div className="kpi">
          <div className="kpi-spark"><Icon name="docs" size={16} className="text-dim"/></div>
          <div className="kpi-label">Total docs on file</div>
          <div className="kpi-value">{DOCUMENTS.length}</div>
          <div className="kpi-meta">across {SUPPLIERS.filter(s => s.status === 'approved').length} active suppliers</div>
        </div>
      </div>

      <div className="filter-bar">
        {[
          { id: 'all', label: 'All' },
          { id: 'red', label: 'Expired/Critical' },
          { id: 'amber', label: 'Expiring 30d' },
          { id: 'green', label: 'Valid' },
        ].map(f => (
          <button key={f.id} className="filter-chip" data-active={filter === f.id} onClick={() => setFilter(f.id)}>{f.label}</button>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center', fontSize: 12, color: 'var(--text-mute)' }}>
          Sort by:
          <select className="filter-chip" value={sort} onChange={e => setSort(e.target.value)} style={{ padding: '5px 10px' }}>
            <option value="expires">Expiration date</option>
            <option value="name">File name</option>
          </select>
        </div>
      </div>

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>Document</th>
              <th>Supplier</th>
              <th>Type</th>
              <th>Uploaded</th>
              <th>Expires</th>
              <th>Days left</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {list.map(d => {
              const days = daysFromNow(d.expires);
              return (
                <tr key={d.id}>
                  <td>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                      <Icon name="file" size={14} className="text-mute"/>
                      <span className="text-mono" style={{ fontSize: 12 }}>{d.fileName}</span>
                    </div>
                  </td>
                  <td>{d.supplier?.name || '—'}</td>
                  <td>{d.type}</td>
                  <td>{fmtDate(d.uploaded)}</td>
                  <td className="text-mono">{fmtDate(d.expires)}</td>
                  <td className="text-mono" style={{ color: days < 0 ? 'var(--red)' : days < 30 ? 'oklch(0.55 0.13 75)' : 'var(--text-mute)', fontWeight: days < 30 ? 600 : 400 }}>
                    {days < 0 ? `${Math.abs(days)}d ago` : `${days}d`}
                  </td>
                  <td><DocPill status={d.status}>{d.status === 'red' ? (days < 0 ? 'Expired' : 'Critical') : d.status === 'amber' ? 'Expiring' : 'Valid'}</DocPill></td>
                  <td><button className="btn btn-sm btn-ghost"><Icon name="moreH" size={13}/></button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const POsPage = ({ company }) => {
  const { POS, SUPPLIERS, SAIF_COMPANIES } = window.SaifData;
  let list = POS;
  if (company !== 'all') list = list.filter(p => p.company === company);
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">POs & Quotes</h1>
          <p className="page-subtitle">Purchase orders and quotes across the group · linked to suppliers</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" size={14}/> Export</button>
          <button className="btn btn-primary"><Icon name="plus" size={14}/> New PO</button>
        </div>
      </div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>Reference</th><th>Description</th><th>Supplier</th><th>Issued by</th><th>Date</th><th style={{ textAlign: 'right' }}>Amount</th><th>Status</th></tr></thead>
          <tbody>
            {list.map(p => {
              const s = SUPPLIERS.find(x => x.id === p.supplierId);
              const co = SAIF_COMPANIES.find(c => c.id === p.company);
              return (
                <tr key={p.id}>
                  <td className="tbl-mono" style={{ color: 'var(--ink)', fontWeight: 500 }}>{p.id}</td>
                  <td>{p.desc}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Avatar name={s.name} size="sm" tone={s.tone}/>
                      <span style={{ fontSize: 12 }}>{s.name}</span>
                    </div>
                  </td>
                  <td><span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span className="company-dot" style={{ background: co.color, width: 7, height: 7, borderRadius: '50%' }}></span>{co.name}</span></td>
                  <td>{fmtDate(p.date)}</td>
                  <td style={{ textAlign: 'right', fontWeight: 600 }}>{fmtCurrency(p.amount)}</td>
                  <td><Badge kind={statusToBadge(p.status)}>{p.status}</Badge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// LOGIN page
const LoginPage = ({ onLogin, onRegister }) => {
  const [tab, setTab] = React.useState('staff');
  return (
    <div className="login-wrap">
      <div className="login-hero">
        <div style={{ position: 'relative', zIndex: 1 }}>
          <SaifLogo size={104}/>
        </div>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 56, fontWeight: 400, letterSpacing: '-0.025em', lineHeight: 1.05, marginBottom: 18, maxWidth: 540 }}>
            <span style={{ fontStyle: 'italic', color: 'oklch(0.85 0.10 65)' }}>One portal</span> <br/>across the entire group.
          </div>
          <div style={{ fontSize: 15, opacity: 0.7, maxWidth: 480, lineHeight: 1.55 }}>
            Saif Al Khyeli Group — Trading. Contracting. Logistics. Facilities. Services. Holdings. <br/>Six companies, one place to manage tasks, suppliers, documents, and approvals.
          </div>
          <div style={{ marginTop: 36, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {window.SaifData.SAIF_COMPANIES.map(c => (
              <div key={c.id} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 12px', background: 'rgba(255,255,255,0.06)', borderRadius: 18, fontSize: 12, border: '1px solid rgba(255,255,255,0.06)' }}>
                <span className="company-dot" style={{ background: c.color, width: 7, height: 7, borderRadius: '50%' }}></span>
                {c.name}
              </div>
            ))}
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 1, fontSize: 11, opacity: 0.4, display: 'flex', gap: 18 }}>
          <a href="#" onClick={e => { e.preventDefault(); window.showToast({ title: 'Opening saifalkhyeli.ae', icon: 'arrowRight' }); }}>← Back to saifalkhyeli.ae</a>
          <span>·</span>
          <a href="#">Privacy</a>
          <span>·</span>
          <a href="#">Help</a>
        </div>
      </div>

      <div className="login-form">
        <h2 style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 6px', color: 'var(--ink)' }}>Sign in</h2>
        <p style={{ fontSize: 13, color: 'var(--text-mute)', margin: '0 0 24px' }}>Welcome back. Sign in to continue.</p>

        <div className="tabs" style={{ marginBottom: 22 }}>
          <button className="tab" data-active={tab === 'staff'} onClick={() => setTab('staff')}>Saif Al Khyeli staff</button>
          <button className="tab" data-active={tab === 'supplier'} onClick={() => setTab('supplier')}>Supplier</button>
        </div>

        <div className="form-row">
          <label className="form-label">{tab === 'supplier' ? 'Supplier email' : 'Work email'}</label>
          <input className="form-control" type="email" defaultValue={tab === 'supplier' ? 'm.chen@northwind.ae' : 'h.alsaif@saifalkhyeli.ae'}/>
        </div>
        <div className="form-row">
          <label className="form-label">Password</label>
          <input className="form-control" type="password" defaultValue="••••••••••"/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, marginBottom: 18 }}>
          <label style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <input type="checkbox" defaultChecked/> Keep me signed in
          </label>
          <a href="#" style={{ color: 'var(--accent-ink)' }}>Forgot password?</a>
        </div>
        <button className="btn btn-primary btn-lg full" style={{ justifyContent: 'center' }} onClick={() => onLogin(tab)}>
          Sign in <Icon name="arrowRight" size={14}/>
        </button>

        {tab === 'staff' && (
          <>
            <div className="divider-text">or</div>
            <button className="btn btn-lg full" style={{ justifyContent: 'center' }} onClick={() => onLogin('staff')}>
              Continue with Saif Al Khyeli SSO
            </button>
          </>
        )}

        {tab === 'supplier' && (
          <div style={{ marginTop: 28, padding: 16, background: 'var(--accent-soft)', borderRadius: 10, fontSize: 13 }}>
            <div style={{ fontWeight: 600, color: 'var(--accent-ink)', marginBottom: 4 }}>New to Saif Al Khyeli Group?</div>
            <div style={{ color: 'var(--text)', marginBottom: 10 }}>Register your business as a supplier and start working with the group.</div>
            <button className="btn btn-accent btn-sm" onClick={onRegister}>
              Register as a supplier <Icon name="arrowRight" size={13}/>
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { DocumentsPage, POsPage, LoginPage });
