// SkinJourney Dashboard — Patients list (grid + table, search, filter)
const { useState: useS_pat, useMemo: useM_pat } = React;

function PatientGridCard({ p, navigate }) {
  return (
    <div
      onClick={() => navigate({ name: 'patient', id: p.id })}
      className="fade-up"
      style={{
        background: 'var(--surface)', border: '1px solid var(--border-subtle)',
        borderRadius: 'var(--radius-xl)', padding: 22,
        cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 16,
        boxShadow: 'var(--elev-1)',
        transition: 'box-shadow var(--dur-standard) var(--ease-emphasized), transform var(--dur-standard) var(--ease-emphasized), border-color var(--dur-standard) var(--ease-standard)',
        position: 'relative',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.boxShadow = 'var(--elev-3)';
        e.currentTarget.style.transform = 'translateY(-2px)';
        e.currentTarget.style.borderColor = 'var(--sage-200)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.boxShadow = 'var(--elev-1)';
        e.currentTarget.style.transform = 'none';
        e.currentTarget.style.borderColor = 'var(--border-subtle)';
      }}
    >
      {p.flagged && (
        <div style={{ position: 'absolute', top: 14, insetInlineStart: 14 }}>
          <Chip kind={p.flagged === 'pending-appointment' ? 'coral' : p.flagged === 'cancelled' ? 'warning' : 'neutral'} dot>
            {p.flagged === 'pending-appointment' ? 'בקשת תור' : p.flagged === 'cancelled' ? 'בוטל' : 'ללא תמונות'}
          </Chip>
        </div>
      )}

      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
        <Avatar name={p.name} size="lg" />
        <div style={{ minWidth: 0, flex: 1, paddingTop: 4 }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--text-primary)', marginBottom: 6 }}>
            {p.name}
          </div>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            <Chip kind="neutral">בת {p.age}</Chip>
            <Chip>עור {p.skin_label}</Chip>
          </div>
        </div>
      </div>

      {/* Mini cadence */}
      <div style={{
        background: 'var(--surface-sunken)', borderRadius: 'var(--radius-md)',
        padding: '14px 16px',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-tertiary)', letterSpacing: 0.4, textTransform: 'uppercase' }}>
            עקביות 8 שבועות
          </span>
          <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
            <span className="tabular" style={{ fontWeight: 700, color: 'var(--text-primary)' }}>{p.photo_count}</span>
            {' '}תמונות
          </span>
        </div>
        <Bars data={p.weekly.slice(-8).concat(Array(Math.max(0, 8 - p.weekly.length)).fill(0)).slice(-8)}
              max={3} width={260} height={48}
              color={p.flagged === 'no-upload' ? 'var(--coral-400)' : 'var(--sage-500)'} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 4 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>
            עדכון אחרון
          </div>
          <div style={{ fontSize: 13, fontWeight: 600, color: p.flagged === 'no-upload' ? 'var(--coral-700)' : 'var(--text-primary)', marginTop: 2 }}>
            {SJ_DATA.formatRelativeHe(p.last_upload)}
          </div>
        </div>
        <span style={{
          color: 'var(--sage-700)', fontSize: 13, fontWeight: 700,
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          צפי בתיק
          <Icon name="arrow_left" size={14} />
        </span>
      </div>
    </div>
  );
}

function PatientTableRow({ p, navigate, i }) {
  return (
    <tr data-flagged={!!p.flagged} onClick={() => navigate({ name: 'patient', id: p.id })}>
      <td>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar name={p.name} size="sm" />
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' }}>{p.name}</div>
            <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>הצטרפה {SJ_DATA.formatRelativeHe(p.joined_at)}</div>
          </div>
        </div>
      </td>
      <td className="tabular" style={{ color: 'var(--text-secondary)' }}>{p.age}</td>
      <td>
        <Chip>{p.skin_label}</Chip>
      </td>
      <td>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {p.focus_labels.slice(0, 2).map((f) => <Chip key={f} kind="neutral">{f}</Chip>)}
        </div>
      </td>
      <td>
        <Bars data={p.weekly.slice(-10).concat(Array(Math.max(0, 10 - p.weekly.length)).fill(0)).slice(-10)} max={3}
              width={140} height={28} color={p.flagged === 'no-upload' ? 'var(--coral-400)' : 'var(--sage-500)'} />
      </td>
      <td className="tabular" style={{ fontWeight: 700, color: 'var(--text-primary)' }}>{p.photo_count}</td>
      <td>
        <span style={{ color: p.flagged === 'no-upload' ? 'var(--coral-700)' : 'var(--text-secondary)', fontSize: 13, fontWeight: 600 }}>
          {SJ_DATA.formatRelativeHe(p.last_upload)}
        </span>
      </td>
      <td>
        {p.flagged && (
          <Chip kind={p.flagged === 'pending-appointment' ? 'coral' : p.flagged === 'cancelled' ? 'warning' : 'neutral'} dot>
            {p.flagged === 'pending-appointment' ? 'בקשת תור' : p.flagged === 'cancelled' ? 'בוטל לאחרונה' : 'ללא תמונות'}
          </Chip>
        )}
      </td>
      <td style={{ width: 1, whiteSpace: 'nowrap' }}>
        <Icon name="arrow_left" size={16} style={{ color: 'var(--text-tertiary)' }} />
      </td>
    </tr>
  );
}

function PatientsScreen({ navigate, route, dataset, onCopyCode }) {
  const [view, setView] = useS_pat(localStorage.getItem('sj-view') || 'grid');
  const [q, setQ] = useS_pat('');
  const [filter, setFilter] = useS_pat(route.filter || 'all');
  const [sort, setSort] = useS_pat('recent');

  const patients = dataset === 'empty' ? [] : SJ_DATA.PATIENTS;

  const filtered = useM_pat(() => {
    let list = patients;
    if (q.trim()) {
      list = list.filter((p) => p.name.includes(q.trim()));
    }
    if (filter === 'attention') list = list.filter((p) => p.flagged);
    else if (filter === 'recent') list = list.filter((p) => p.last_upload_days_ago <= 7);
    else if (filter === 'inactive') list = list.filter((p) => p.last_upload_days_ago > 14);

    list = [...list];
    if (sort === 'recent') list.sort((a, b) => a.last_upload_days_ago - b.last_upload_days_ago);
    else if (sort === 'name') list.sort((a, b) => a.name.localeCompare(b.name, 'he'));
    else if (sort === 'count') list.sort((a, b) => b.photo_count - a.photo_count);
    return list;
  }, [patients, q, filter, sort]);

  const setViewAndSave = (v) => { setView(v); localStorage.setItem('sj-view', v); };

  return (
    <div className="screen content-scroll">
      <PageHeader
        title="מטופלות"
        subtitle={`${patients.length} מטופלות מחוברות${filtered.length !== patients.length ? ` · ${filtered.length} מוצגות` : ''}`}
        actions={
          <Segmented value={view} onChange={setViewAndSave} options={[
            { value: 'grid', label: 'כרטיסיות', icon: 'grid' },
            { value: 'table', label: 'טבלה', icon: 'list' },
          ]} />
        }
      />

      {/* Filter bar */}
      <div style={{
        display: 'flex', gap: 12, alignItems: 'center', marginBottom: 20, flexWrap: 'wrap',
      }}>
        <div className="search" style={{ flex: 1, maxWidth: 360 }}>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="חיפוש לפי שם..." />
          <Icon name="search" className="icon" size={16} />
        </div>
        <Segmented value={filter} onChange={setFilter} options={[
          { value: 'all', label: `הכל · ${patients.length}` },
          { value: 'attention', label: `דורשות תשומת לב · ${patients.filter((p) => p.flagged).length}` },
          { value: 'recent', label: 'פעילות השבוע' },
          { value: 'inactive', label: 'לא העלו לאחרונה' },
        ]} />
        <div style={{ marginInlineStart: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>מיון:</span>
          <select className="select" value={sort} onChange={(e) => setSort(e.target.value)}
                  style={{ width: 'auto', padding: '8px 32px 8px 12px' }}>
            <option value="recent">פעילות אחרונה</option>
            <option value="name">לפי שם</option>
            <option value="count">מספר תמונות</option>
          </select>
        </div>
      </div>

      {patients.length === 0 ? (
        <Card flat sunken style={{ padding: 0 }}>
          <Empty
            icon="leaf"
            title="עוד אין מטופלות במרפאה"
            body="שלחי את קוד ההצטרפות שלך — ברגע שהמטופלת תזין אותו באפליקציה, היא תופיע כאן."
            action={<Button kind="primary" icon="copy" onClick={onCopyCode}>העתיקי את הקוד שלי</Button>}
          />
        </Card>
      ) : filtered.length === 0 ? (
        <Card flat sunken style={{ padding: 0 }}>
          <Empty icon="search" title="אין תוצאות"
                 body={q ? `לא נמצאה מטופלת בשם "${q}"` : 'נסי סינון אחר'} />
        </Card>
      ) : view === 'grid' ? (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
          {filtered.map((p, i) => <PatientGridCard key={p.id} p={p} navigate={navigate} />)}
        </div>
      ) : (
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>מטופלת</th>
                <th>גיל</th>
                <th>סוג עור</th>
                <th>תחומי טיפול</th>
                <th>עקביות 10 שבועות</th>
                <th>תמונות</th>
                <th>עדכון אחרון</th>
                <th>סטטוס</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p, i) => <PatientTableRow key={p.id} p={p} navigate={navigate} i={i} />)}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

window.PatientsScreen = PatientsScreen;
