// Screen · Tasks & Goals  [BETA]
// Daily work surface + goal tracking. Two tabs:
//  · Today — prioritized to-dos pulled from boards/deadlines, plus what
//    you're waiting on from other people.
//  · Goals — personal + shared department goals with pacing. Progress is
//    framed as "auto-measured from data sources" (NalarX is connected to
//    the underlying systems), not manual check-ins.
// Mock data only — this is a design preview for a later build.

const TASKS_MOCK = [
 { id: 't1', title: 'Recap payroll for month 3', dept: 'Finance', due: 'Today · 5 PM', dueTone: 'warn', bucket: 'today' },
 { id: 't2', title: 'Review ACE campaign from Marketing', dept: 'Marketing', due: 'Today', dueTone: 'warn', bucket: 'today' },
 { id: 't3', title: 'Approve 3 reimbursements > Rp 5jt', dept: 'Finance', due: 'Today', dueTone: 'warn', bucket: 'today' },
 { id: 't4', title: 'Draft Q2 vendor consolidation memo', dept: 'Procurement', due: 'Jun 15', bucket: 'week' },
 { id: 't5', title: 'Update fraud threshold doc', dept: 'Risk', due: 'Fri', bucket: 'week' },
 { id: 't6', title: 'Sign off SOC 2 access review', dept: 'Compliance', due: 'next Mon', bucket: 'week' },
 { id: 't7', title: 'Q2 vendor memo — legal sign-off', dept: 'Procurement', waitingOn: 'Legal · Hadi', bucket: 'waiting' },
 { id: 't8', title: 'ACE campaign assets', dept: 'Marketing', waitingOn: 'Design team', bucket: 'waiting' },
];

const MY_GOALS_MOCK = [
 {
 id: 'g1', title: 'Achieve 100 new customers', period: 'May', status: 'at-risk',
 metric: '40 of 100 · 60 to go in 7 days', source: 'Salesforce · opportunities',
 todos: [
 { id: 'g1a', label: 'Follow up 12 warm leads in pipeline', due: 'Today' },
 { id: 'g1b', label: 'Push referral campaign to existing customers', due: 'Wed' },
 { id: 'g1c', label: 'Close 3 deals in final negotiation', due: 'Fri' },
 ],
 },
 {
 id: 'g2', title: 'Close 3 payroll runs on time', period: 'May', status: 'on-track',
 metric: '2 of 3 runs · 1 left', source: 'HRIS · payroll',
 todos: [
 { id: 'g2a', label: 'Run month-3 payroll batch', due: 'Fri' },
 { id: 'g2b', label: 'Verify 4 flagged salary adjustments' },
 ],
 },
 {
 id: 'g3', title: 'Cut vendor spend by 8%', period: 'Q2', status: 'behind',
 metric: '5.2% of 8% · need +2.8%', source: 'Postgres · invoices',
 todos: [
 { id: 'g3a', label: 'Renegotiate top-5 vendor contracts', due: 'Jun 10' },
 { id: 'g3b', label: 'Cancel 3 duplicate SaaS subscriptions' },
 { id: 'g3c', label: 'Move 2 vendors to e-invoicing discount' },
 ],
 },
];

const DEPT_GOALS_MOCK = [
 {
 id: 'd1', title: 'Reconciliation accuracy ≥ 99%', period: 'May', owner: 'Finance dept', status: 'on-track',
 metric: '98.2% of 99% target', source: 'Postgres · gl_journal',
 todos: [
 { id: 'd1a', label: 'Clear 14 unreconciled GL entries', due: 'This week' },
 { id: 'd1b', label: 'Fix 2 recurring mapping rules' },
 ],
 },
 {
 id: 'd2', title: 'Onboard 12 vendors to e-invoicing', period: 'Q2', owner: 'Finance dept', status: 'on-track',
 metric: '9 of 12 · 3 to go', source: 'Coupa · vendors',
 todos: [
 { id: 'd2a', label: 'Onboard 3 remaining vendors (invites sent)' },
 { id: 'd2b', label: 'Confirm e-invoice format with Coupa' },
 ],
 },
];

const GOAL_STATUS = {
 'on-track': { label: 'On track', cls: 'ok', color: 'var(--ok)' },
 'at-risk': { label: 'At risk', cls: 'warn', color: 'var(--warn)' },
 'behind': { label: 'Behind', cls: 'err', color: 'var(--err)' },
};

const TasksTabs = ({ tab, setTab }) => (
 <div style={{ display: 'flex', gap: 2, padding: 2, background: 'var(--bg-sunken)', border: '0.5px solid var(--line)', borderRadius: 8 }}>
 {[['today', 'Today', 'check-circle'], ['goals', 'Goals', 'target']].map(([id, label, icon]) => (
 <button key={id} onClick={() => setTab(id)}
 style={{
 display: 'flex', alignItems: 'center', gap: 6, height: 28, padding: '0 12px',
 border: 0, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5,
 fontWeight: tab === id ? 550 : 450,
 background: tab === id ? 'var(--bg-elev)' : 'transparent',
 color: tab === id ? 'var(--ink)' : 'var(--ink-3)',
 boxShadow: tab === id ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
 transition: 'background .12s, color .12s',
 }}>
 <Icon name={icon} size={14} /> {label}
 </button>
 ))}
 </div>
);

const TaskRow = ({ task, checked, onToggle }) => (
 <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11, padding: '11px 0', borderBottom: '0.5px solid var(--line)' }}>
 <button onClick={onToggle} aria-label="Toggle task"
 style={{
 marginTop: 1, width: 18, height: 18, flexShrink: 0, borderRadius: 6, cursor: 'pointer', padding: 0,
 border: '1.5px solid ' + (checked ? 'var(--ok)' : 'var(--line-strong)'),
 background: checked ? 'var(--ok)' : 'transparent',
 display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background .12s, border-color .12s',
 }}>
 {checked && <Icon name="check" size={12} style={{ color: 'white' }} />}
 </button>
 <div style={{ flex: 1, minWidth: 0 }}>
 <div style={{ fontSize: 13, color: checked ? 'var(--ink-4)' : 'var(--ink)', textDecoration: checked ? 'line-through' : 'none' }}>
 {task.title}
 </div>
 <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6 }}>
 {task.dept && <span className="nx-chip" style={{ height: 20, fontSize: 10.5 }}>{task.dept}</span>}
 {task.due && <span className={'nx-chip' + (task.dueTone ? ' ' + task.dueTone : '')} style={{ height: 20, fontSize: 10.5 }}><Icon name="clock" size={10} /> {task.due}</span>}
 {task.waitingOn && <span className="nx-chip" style={{ height: 20, fontSize: 10.5 }}><Icon name="route" size={10} /> Waiting · {task.waitingOn}</span>}
 </div>
 </div>
 </div>
);

const TaskSection = ({ label, count, children }) => (
 <div style={{ marginBottom: 22 }}>
 <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>
 {label} · {count}
 </div>
 {children}
 </div>
);

const TodayTab = () => {
 const [done, setDone] = React.useState({});
 const toggle = (id) => setDone(d => ({ ...d, [id]: !d[id] }));
 const today = TASKS_MOCK.filter(t => t.bucket === 'today');
 const week = TASKS_MOCK.filter(t => t.bucket === 'week');
 const waiting = TASKS_MOCK.filter(t => t.bucket === 'waiting');
 const doneCount = today.filter(t => done[t.id]).length;

 return (
 <div style={{ maxWidth: 720 }}>
 {/* Day summary */}
 <div className="nx-card" style={{ padding: 14, marginBottom: 22, display: 'flex', alignItems: 'center', gap: 12, background: 'var(--bg-elev)' }}>
 <div style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
 <Icon name="check-circle" size={20} />
 </div>
 <div style={{ flex: 1 }}>
 <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>
 {doneCount} of {today.length} due today done
 </div>
 <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 1 }}>
 {waiting.length} blocked on other people · {week.length} coming up this week
 </div>
 </div>
 <span className="nx-chip" style={{ height: 22, fontSize: 11 }}><Icon name="sparkle" size={11} /> Recap via Nalar</span>
 </div>

 <TaskSection label="Due today" count={today.length}>
 {today.map(t => <TaskRow key={t.id} task={t} checked={!!done[t.id]} onToggle={() => toggle(t.id)} />)}
 </TaskSection>

 <TaskSection label="Waiting on others" count={waiting.length}>
 {waiting.map(t => <TaskRow key={t.id} task={t} checked={!!done[t.id]} onToggle={() => toggle(t.id)} />)}
 </TaskSection>

 <TaskSection label="This week" count={week.length}>
 {week.map(t => <TaskRow key={t.id} task={t} checked={!!done[t.id]} onToggle={() => toggle(t.id)} />)}
 </TaskSection>
 </div>
 );
};

const GoalTodo = ({ todo, checked, onToggle, isLast }) => (
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', borderBottom: isLast ? 'none' : '0.5px solid var(--line)' }}>
 <button onClick={onToggle} aria-label="Toggle action"
 style={{
 width: 17, height: 17, flexShrink: 0, borderRadius: 6, cursor: 'pointer', padding: 0,
 border: '1.5px solid ' + (checked ? 'var(--ok)' : 'var(--line-strong)'),
 background: checked ? 'var(--ok)' : 'transparent',
 display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background .12s, border-color .12s',
 }}>
 {checked && <Icon name="check" size={11} style={{ color: 'white' }} />}
 </button>
 <span style={{ flex: 1, minWidth: 0, fontSize: 12.5, color: checked ? 'var(--ink-4)' : 'var(--ink-2)', textDecoration: checked ? 'line-through' : 'none' }}>
 {todo.label}
 </span>
 {todo.due && <span className="nx-chip" style={{ height: 19, fontSize: 10, flexShrink: 0 }}><Icon name="clock" size={9} /> {todo.due}</span>}
 </div>
);

const GoalCard = ({ goal }) => {
 const m = GOAL_STATUS[goal.status];
 const [done, setDone] = React.useState({});
 const toggle = (id) => setDone(d => ({ ...d, [id]: !d[id] }));
 const total = goal.todos.length;
 const doneN = goal.todos.filter(t => done[t.id]).length;

 return (
 <div className="nx-card" style={{ padding: 16, background: 'var(--bg-elev)' }}>
 {/* Goal header — status + concise metric, no bar */}
 <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
 <div style={{ flex: 1, minWidth: 0 }}>
 <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{goal.title}</div>
 <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 3 }}>
 {goal.period}{goal.owner ? ' · ' + goal.owner : ''} · <span style={{ color: m.color, fontWeight: 500 }}>{goal.metric}</span>
 </div>
 </div>
 <span className={'nx-chip ' + m.cls} style={{ height: 20, fontSize: 10.5, padding: '0 8px' }}>{m.label}</span>
 </div>

 {/* What to do to hit it */}
 <div style={{ marginTop: 13 }}>
 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 10, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 2 }}>
 <span>To do to hit this</span>
 <span>{doneN}/{total}</span>
 </div>
 {goal.todos.map((t, i) => (
 <GoalTodo key={t.id} todo={t} checked={!!done[t.id]} onToggle={() => toggle(t.id)} isLast={i === total - 1} />
 ))}
 </div>

 <div style={{ marginTop: 12, paddingTop: 9, borderTop: '0.5px solid var(--line)', fontSize: 10.5, color: 'var(--ink-4)', display: 'flex', alignItems: 'center', gap: 5 }}>
 <Icon name="database" size={11} /> Auto-tracked from {goal.source}
 </div>
 </div>
 );
};

const GoalsTab = () => (
 <div style={{ maxWidth: 920 }}>
 <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
 My goals · {MY_GOALS_MOCK.length}
 </div>
 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 12, marginBottom: 26 }}>
 {MY_GOALS_MOCK.map(g => <GoalCard key={g.id} goal={g} />)}
 </div>

 <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 12 }}>
 <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
 Department goals · Finance
 </span>
 <span className="nx-chip" style={{ height: 18, fontSize: 9.5, padding: '0 7px' }}><Icon name="users" size={10} /> Shared</span>
 </div>
 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 12 }}>
 {DEPT_GOALS_MOCK.map(g => <GoalCard key={g.id} goal={g} />)}
 </div>
 </div>
);

const ScreenTasks = () => {
 const [tab, setTab] = React.useState('today');

 return (
 <div className="nx-page" style={{ padding: '24px 32px 40px', maxWidth: 1100, margin: '0 auto' }}>
 {/* Header */}
 <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18, gap: 16 }}>
 <div>
 <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
 <h1 style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>Tasks & Goals</h1>
 <span style={{ fontSize: 9, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--accent-ink)', background: 'var(--accent-soft)', padding: '2px 7px', borderRadius: 999 }}>Beta</span>
 </div>
 <div style={{ marginTop: 4, color: 'var(--ink-3)', fontSize: 13 }}>
 Your day and your goals — pulled from boards, deadlines, and connected data.
 </div>
 </div>
 <TasksTabs tab={tab} setTab={setTab} />
 </div>

 {tab === 'today' ? <TodayTab /> : <GoalsTab />}
 </div>
 );
};

window.ScreenTasks = ScreenTasks;
