// app.jsx — App shell: Sidebar, TopBar, NewTaskModal, App root

const { useState: useApp, useEffect: useAppEffect } = React;

// ── Nav items ─────────────────────────────────────────────────

const NAV = [
  { id: 'tasks',     label: 'Tasks',     icon: 'tasks'     },
  { id: 'customers', label: 'Customers', icon: 'customers' },
  { id: 'classes',   label: 'Classes',   icon: 'classes'   },
  { id: 'curriculum',label: 'Curriculum',icon: 'curriculum'},
  { id: 'printing',  label: 'Printing',  icon: 'printing'  },
  { id: 'invoices',  label: 'Invoices',  icon: 'invoices'  },
  { id: 'staff',     label: 'Staff',     icon: 'staff'     },
  { id: 'emails',    label: 'Emails',    icon: 'emails'    },
  { id: 'forms',     label: 'Forms',     icon: 'forms'     },
  { id: 'settings',  label: 'Settings',  icon: 'settings'  },
];

// ── New Task Modal ────────────────────────────────────────────

function NewTaskModal({ open, onClose }) {
  const [type,     setType]     = useApp('');
  const [notes,    setNotes]    = useApp('');
  const [assignee, setAssignee] = useApp('Maya Rodriguez (you)');

  const reset = () => { setType(''); setNotes(''); };
  const close = () => { reset(); onClose(); };
  const save  = () => { reset(); onClose(); };

  return (
    <Modal open={open} onClose={close} title="New task" width={540}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>

        <TMSelect label="Task type" value={type} onChange={setType} options={[
          { value: '',               label: 'Select a type…' },
          { value: 'follow-up',      label: 'Follow up with customer' },
          { value: 'print-supp',     label: 'Print supplementary material' },
          { value: 'raise-request',  label: 'Raise request on behalf of tutor' },
          { value: 'generic',        label: 'Generic task' },
        ]} />

        {type === 'follow-up' && <>
          <TMSelect label="Customer" value="" onChange={() => {}} options={[
            { value: '', label: 'Search customer…' },
            ...SAMPLE_STUDENTS.map(s => ({ value: s.id, label: `${s.firstName} ${s.lastName} — ${s.course}` })),
          ]} />
          <Textarea label="Reason" value={notes} onChange={setNotes} placeholder="Why are you following up?" rows={2} />
          <Input label="Follow-up date" type="date" value="" onChange={() => {}} />
        </>}

        {type === 'print-supp' && <>
          <TMSelect label="Class" value="" onChange={() => {}} options={[
            { value: '', label: 'Search class…' },
            ...SAMPLE_CLASSES.map(c => ({ value: c.id, label: classLabel(c) })),
          ]} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <Input label="Copies" value="1" onChange={() => {}} type="number" />
            <TMSelect label="Paper size" value="A4" onChange={() => {}} options={['A4','A3']} />
          </div>
          <Input label="Due by" type="date" value="" onChange={() => {}} />
        </>}

        {type === 'raise-request' && <>
          <TMSelect label="Tutor" value="" onChange={() => {}} options={[
            { value: '', label: 'Select tutor…' },
            ...SAMPLE_STAFF.filter(s => s.role.toLowerCase().includes('tutor')).map(s => ({ value: s.id, label: `${s.firstName} ${s.lastName}` })),
          ]} />
          <TMSelect label="Category" value="Supplies" onChange={() => {}} options={['Supplies','Cleaning','Material','Other']} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <TMSelect label="Campus" value="Parramatta" onChange={() => {}} options={['Parramatta','Bella Vista']} />
            <Input label="Room (optional)" value="" onChange={() => {}} placeholder="Room 3" />
          </div>
          <Textarea label="Description" value={notes} onChange={setNotes} rows={2} />
          <TMSelect label="Urgency" value="medium" onChange={() => {}} options={['low','medium','high']} />
        </>}

        {type === 'generic' && <>
          <Input label="Title" value="" onChange={() => {}} placeholder="Task title" />
          <Textarea label="Description (optional)" value={notes} onChange={setNotes} rows={2} />
        </>}

        {type && <>
          <div style={{ height: 1, background: 'var(--border-soft)' }} />
          <TMSelect label="Assignee" value={assignee} onChange={setAssignee}
            options={['Maya Rodriguez (you)','Jamie Liu','Taylor Kim']} />
          <Input label="Due date" type="date" value="" onChange={() => {}} />
          <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', paddingTop: '4px' }}>
            <Button variant="secondary" onClick={close}>Cancel</Button>
            <Button variant="primary"   onClick={save}>Save task</Button>
          </div>
        </>}
      </div>
    </Modal>
  );
}

// ── Sidebar ───────────────────────────────────────────────────

function Sidebar({ active, onNav, collapsed }) {
  return (
    <div style={{ width: collapsed ? 56 : 190, flexShrink: 0, background: 'var(--bg-surface-muted)',
      borderRight: '1px solid var(--border-soft)', display: 'flex', flexDirection: 'column',
      transition: 'width 180ms cubic-bezier(.2,.7,.3,1)', overflow: 'hidden' }}>

      {/* Logo */}
      <div style={{ height: 56, display: 'flex', alignItems: 'center', flexShrink: 0,
        justifyContent: collapsed ? 'center' : 'flex-start', padding: collapsed ? 0 : '0 16px',
        borderBottom: '1px solid var(--border-soft)', gap: '10px' }}>
        <div style={{ width: 28, height: 28, borderRadius: '6px', background: '#1F4D3D', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: '12px', fontWeight: 700, color: '#FBFAF6', letterSpacing: '-0.02em' }}>TM</div>
        {!collapsed && (
          <span style={{ fontSize: '13px', fontWeight: 600, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden' }}>
            The Mathologists
          </span>
        )}
      </div>

      {/* Nav items */}
      <nav style={{ flex: 1, padding: '6px 0', overflowY: 'auto' }}>
        {NAV.map(item => {
          const on = active === item.id;
          return (
            <button key={item.id} onClick={() => onNav(item.id)} title={collapsed ? item.label : undefined}
              style={{ width: '100%', display: 'flex', alignItems: 'center',
                gap: '10px', padding: collapsed ? '11px 0' : '10px 16px',
                justifyContent: collapsed ? 'center' : 'flex-start',
                background: on ? 'rgba(31,77,61,0.15)' : 'transparent',
                border: 'none', borderLeft: `3px solid ${on ? '#1F4D3D' : 'transparent'}`,
                cursor: 'pointer', fontFamily: 'inherit',
                color: on ? 'var(--text-primary)' : 'var(--text-secondary)',
                transition: '100ms ease', fontSize: '13px', fontWeight: on ? 500 : 400 }}
              onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)'; }}
              onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}
            >
              <Icon name={item.icon} size={17} color={on ? '#4A9B7E' : 'currentColor'} />
              {!collapsed && <span>{item.label}</span>}
            </button>
          );
        })}
      </nav>

      {/* User */}
      <div style={{ borderTop: '1px solid var(--border-soft)', padding: collapsed ? '12px 0' : '12px 14px',
        display: 'flex', alignItems: 'center', justifyContent: collapsed ? 'center' : 'flex-start', gap: '8px' }}>
        <Avatar name="Maya Rodriguez" size={28} />
        {!collapsed && (
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: '12px', fontWeight: 500, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>Maya Rodriguez</div>
            <div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>Reception · Parra</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Top Bar ───────────────────────────────────────────────────

function TopBar({ onNewTask, collapsed, onToggle, light, onToggleLight, showData, onOpenCalendar }) {
  const now = new Date();
  const dayName = now.toLocaleDateString('en-AU', { weekday: 'long' });
  const dateStr = now.toLocaleDateString('en-AU', { day: 'numeric', month: 'long', year: 'numeric' });
  // Glanceable reception stats — enrolled headcount, then the day's action items.
  const enrolled     = SAMPLE_STUDENTS.filter(s => s.status === 'enrolled' && s.classId).length;
  const trialsBooked = SAMPLE_STUDENTS.filter(s => s.status === 'trial').length;
  const leads        = SAMPLE_STUDENTS.filter(s => s.status === 'lead').length;
  const stats = [
    { dot: '#4A9B7E', value: enrolled,     label: `enrolled student${enrolled === 1 ? '' : 's'}` },
    { dot: '#4A8BB2', value: trialsBooked, label: `trial${trialsBooked === 1 ? '' : 's'} booked` },
    { dot: '#C9A227', value: leads,        label: `lead${leads === 1 ? '' : 's'} to follow up` },
  ];

  return (
    <div style={{ height: 56, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '0 20px 0 12px', borderBottom: '1px solid var(--border-soft)',
      background: 'var(--bg-body)', flexShrink: 0, gap: '12px' }}>

      <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
        {/* Sidebar toggle */}
        <button onClick={onToggle} style={{ background: 'none', border: 'none', cursor: 'pointer',
          padding: '6px', borderRadius: '4px', color: 'var(--text-muted)', display: 'flex', alignItems: 'center' }}>
          <Icon name="menu" size={18} />
        </button>

        {/* Today's date & day */}
        <div style={{ display: 'flex', alignItems: 'center', gap: '9px' }}>
          <Icon name="calendar" size={17} color="var(--text-muted)" />
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--text-primary)' }}>{dayName}</div>
            <div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>{dateStr}</div>
          </div>
        </div>

        {/* Live term + week */}
        {(() => { const tw = currentTermWeek(); return (
          <div title="Current term & week" style={{ display: 'inline-flex', alignItems: 'center', gap: '7px', whiteSpace: 'nowrap',
            background: tw.inTerm ? 'rgba(31,77,61,0.15)' : 'var(--bg-surface-muted)',
            border: `1px solid ${tw.inTerm ? 'rgba(31,77,61,0.35)' : 'var(--border-default)'}`, borderRadius: '6px', padding: '4px 10px' }}>
            {tw.inTerm ? (
              <React.Fragment>
                <span style={{ fontSize: '12px', fontWeight: 600, color: '#4A9B7E' }}>{tw.term}</span>
                <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'rgba(74,155,126,0.55)' }} />
                <span style={{ fontSize: '12px', fontWeight: 600, color: '#4A9B7E' }}>Week {tw.week}</span>
              </React.Fragment>
            ) : (
              <span style={{ fontSize: '12px', fontWeight: 500, color: 'var(--text-muted)' }}>School holidays</span>
            )}
          </div>
        ); })()}

        {/* Glanceable stats */}
        {showData && (
          <React.Fragment>
            <div style={{ width: 1, height: 28, background: 'var(--border-soft)' }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
              {stats.map(s => (
                <span key={s.label} title={s.label} style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: s.dot, flexShrink: 0 }} />
                  <strong style={{ color: 'var(--text-primary)', fontWeight: 600 }}>{s.value}</strong> {s.label}
                </span>
              ))}
            </div>
          </React.Fragment>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
        {/* Term calendar */}
        <button onClick={onOpenCalendar} title="Term calendar"
          style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-default)',
            borderRadius: '4px', padding: '6px 10px', cursor: 'pointer', display: 'flex', alignItems: 'center',
            gap: '5px', fontSize: '12px', color: 'var(--text-secondary)', fontFamily: 'inherit' }}>
          <Icon name="calendar" size={14} />
          Calendar
        </button>

        {/* Theme toggle */}
        <button onClick={onToggleLight} title="Toggle light/dark"
          style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-default)',
            borderRadius: '4px', padding: '6px 10px', cursor: 'pointer', display: 'flex', alignItems: 'center',
            gap: '5px', fontSize: '12px', color: 'var(--text-secondary)', fontFamily: 'inherit' }}>
          <Icon name={light ? 'moon' : 'sun'} size={14} />
          {light ? 'Dark' : 'Light'}
        </button>

        <Button variant="primary" onClick={onNewTask}
          icon={<Icon name="plus" size={14} color="#FBFAF6" />}>
          New Task
        </Button>
      </div>
    </div>
  );
}

// ── App Root ──────────────────────────────────────────────────

function applyTheme(light) {
  const r = document.documentElement.style;
  if (light) {
    r.setProperty('--bg-body',         '#FAF9F5');
    r.setProperty('--bg-surface',      '#FBFAF6');
    r.setProperty('--bg-elevated',     '#FFFFFF');
    r.setProperty('--bg-surface-muted','#E8E4D6');
    r.setProperty('--bg-hover',        'rgba(0,0,0,0.04)');
    r.setProperty('--bg-selected',     'rgba(31,77,61,0.08)');
    r.setProperty('--text-primary',    '#1A1815');
    r.setProperty('--text-secondary',  '#5A574E');
    r.setProperty('--text-muted',      '#9A9A9A');
    r.setProperty('--border-default',  '#E8E4D6');
    r.setProperty('--border-soft',     '#EDEAD9');
  } else {
    r.setProperty('--bg-body',         '#1A1815');
    r.setProperty('--bg-surface',      '#25221E');
    r.setProperty('--bg-elevated',     '#2F2B26');
    r.setProperty('--bg-surface-muted','#211E1A');
    r.setProperty('--bg-hover',        'rgba(255,255,255,0.04)');
    r.setProperty('--bg-selected',     'rgba(31,77,61,0.15)');
    r.setProperty('--text-primary',    '#FBFAF6');
    r.setProperty('--text-secondary',  '#B8B2A4');
    r.setProperty('--text-muted',      '#7A7367');
    r.setProperty('--border-default',  '#3A3530');
    r.setProperty('--border-soft',     '#2F2B26');
  }
}

function App() {
  const [section,   setSection]   = useApp('tasks');
  const [collapsed, setCollapsed] = useApp(false);
  const [taskOpen,  setTaskOpen]  = useApp(false);
  const [light,     setLight]     = useApp(false);
  const [showData,  setShowData]  = useApp(true);
  const [tweaksOpen,setTweaksOpen]= useApp(false);
  const [calOpen,   setCalOpen]   = useApp(false);

  // Customer drawer lifted to app level (opened from Tasks board)
  const [custOpen, setCustOpen] = useApp(false);
  const [custSel,  setCustSel]  = useApp(null);

  useAppEffect(() => { applyTheme(light); }, [light]);

  // Tweaks panel protocol
  useAppEffect(() => {
    const handler = e => {
      if (e.data?.type === '__activate_edit_mode')   setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const openCustomer = student => { setCustSel(student); setCustOpen(true); };

  const renderSection = () => {
    switch (section) {
      case 'tasks':     return <TasksBoard     showData={showData} onOpenCustomer={openCustomer} />;
      case 'customers': return <CustomersSection showData={showData} />;
      case 'emails':    return <EmailsSection />;
      case 'forms':     return <FormsSection />;
      case 'staff':     return <StaffSection   showData={showData} />;
      case 'classes':   return <ClassesSection  showData={showData} />;
      case 'curriculum':return <CurriculumSection />;
      case 'printing':  return <PrintingSection  showData={showData} />;
      case 'invoices':  return <InvoicesSection  showData={showData} />;
      case 'settings':  return <SettingsSection />;
      default:          return null;
    }
  };

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden',
      background: 'var(--bg-body)', color: 'var(--text-primary)',
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
      fontSize: '14px', lineHeight: 1.5 }}>

      <Sidebar active={section} onNav={setSection} collapsed={collapsed} />

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
        <TopBar
          onNewTask={() => setTaskOpen(true)}
          collapsed={collapsed} onToggle={() => setCollapsed(c => !c)}
          light={light} onToggleLight={() => setLight(l => !l)}
          showData={showData}
          onOpenCalendar={() => setCalOpen(true)}
        />
        <div style={{ flex: 1, overflowY: 'auto', padding: section === 'tasks' ? '20px 24px 0' : '24px 32px' }}>
          {renderSection()}
        </div>
      </div>

      <NewTaskModal open={taskOpen} onClose={() => setTaskOpen(false)} />

      <TermCalendarModal open={calOpen} onClose={() => setCalOpen(false)} />

      {/* Customer drawer (from Tasks board "Open" action) */}
      <CustomerDrawer customer={custSel} open={custOpen} onClose={() => setCustOpen(false)} />

      {/* Tweaks panel */}
      {tweaksOpen && (
        <TweaksPanel onClose={() => {
          setTweaksOpen(false);
          window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
        }}>
          <TweakSection title="Appearance">
            <TweakToggle label="Light mode" value={light} onChange={setLight} />
          </TweakSection>
          <TweakSection title="Layout">
            <TweakToggle label="Collapse sidebar" value={collapsed} onChange={setCollapsed} />
          </TweakSection>
          <TweakSection title="Sample data">
            <TweakToggle label="Show sample data" value={showData} onChange={setShowData} />
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
