/* Atlas Ledger — Tasks page: open task list, work on anything in any order.
   Each task expands inline; no forced sequence. Confirm unlocks after the 2 answers. */

const CLOSE_QUESTIONS = [
  {
    id: 'q1', tag: 'Bank line · no document', amount: '− HKD 52,000', when: '15 May · transfer to WK Logistics',
    q: 'What was this?',
    chips: [
      { l: 'Logistics cost', hint: 'suggested' }, { l: 'Supplier payment' },
      { l: "Director's loan" }, { l: 'Staff reimbursement' },
    ],
    foot: 'Your team suggests “Logistics cost” — all 9 past WK Logistics payments were logistics.',
  },
  {
    id: 'q2', tag: 'Bank line · no document', amount: '− HKD 8,000', when: '6 May · ATM withdrawal',
    q: 'What was this for?',
    chips: [
      { l: 'Petty cash', hint: 'suggested' }, { l: 'Staff advance' },
      { l: "Director's drawing" }, { l: 'Office supplies' },
    ],
    foot: 'Cash withdrawals are usually petty cash for ABC Trading.',
  },
];

/* ── expanded bodies ── */

function QuestionBody({ def, onCommit, go }) {
  const [picked, setPicked] = React.useState(null);
  const [custom, setCustom] = React.useState('');
  const answer = custom.trim() || picked;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
        <span className="hb-num" style={{ fontSize: 24, fontWeight: 700 }}>{def.amount}</span>
        <span style={{ fontSize: 13, color: 'var(--hb-muted)' }}>{def.when}</span>
      </div>
      <div style={{ fontSize: 14.5, fontWeight: 700, marginTop: 12 }}>{def.q}</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 8, marginTop: 10 }}>
        {def.chips.map((c) => {
          const sel = picked === c.l && !custom.trim();
          return (
            <button key={c.l} onClick={() => { setPicked(sel ? null : c.l); setCustom(''); }} style={{
              height: 42, borderRadius: 10, fontFamily: 'var(--hb-grot)',
              border: sel ? '1.5px solid var(--hb-teal)' : '1px solid var(--hb-line)',
              background: sel ? 'var(--hb-teal-tint)' : '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              fontSize: 13, fontWeight: sel ? 700 : 500, color: sel ? 'var(--hb-teal-deep)' : 'var(--hb-ink)', cursor: 'pointer',
            }}>
              {c.l}
              {c.hint ? <span style={{ fontSize: 10, color: 'var(--hb-teal)', fontWeight: 700 }}>· {c.hint}</span> : null}
            </button>
          );
        })}
      </div>
      {/* free-text answer — always available */}
      <input
        value={custom}
        onChange={(e) => { setCustom(e.target.value); if (e.target.value.trim()) setPicked(null); }}
        placeholder="Or type your own answer…"
        style={{
          width: '100%', height: 42, marginTop: 8, borderRadius: 10, padding: '0 14px',
          border: custom.trim() ? '1.5px solid var(--hb-teal)' : '1px solid var(--hb-line)',
          background: custom.trim() ? 'var(--hb-teal-tint)' : '#fff',
          fontSize: 13, fontFamily: 'var(--hb-grot)', color: 'var(--hb-ink)', outline: 'none', boxSizing: 'border-box',
        }}
      />
      <div style={{ fontSize: 11.5, color: 'var(--hb-faint)', marginTop: 10 }}>{def.foot}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 14, flexWrap: 'wrap' }}>
        <button className="hb-btn" disabled={!answer} onClick={() => onCommit(answer)} style={{ height: 44, fontSize: 14, padding: '0 22px' }}>
          {answer ? 'Confirm: ' + answer.toLowerCase() : 'Pick or type an answer'}
        </button>
        <a className="hb-link" style={{ fontSize: 12.5, color: 'var(--hb-muted)' }} onClick={() => go('messages')}>Not sure? Ask your team →</a>
      </div>
      {/* upload receipt — separate, always-present channel */}
      <div onClick={() => onCommit('Receipt uploaded · your team will match it')} style={{
        marginTop: 14, border: '1.5px dashed var(--hb-line)', borderRadius: 10, background: '#fff',
        padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
      }}>
        <HIcon name="upload" size={17} color="var(--hb-teal)" />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Have the receipt? Upload it instead</div>
          <div style={{ fontSize: 11.5, color: 'var(--hb-muted)', marginTop: 1 }}>Drag &amp; drop, or WhatsApp a photo — we'll match and book it for you</div>
        </div>
        <HIcon name="chevR" size={15} color="var(--hb-faint)" />
      </div>
    </div>
  );
}

function SignBody({ onSign }) {
  return (
    <div>
      <div style={{ fontSize: 13.5, color: 'var(--hb-muted)' }}>Year of assessment 2025/26 · prepared and checked by your accounting team</div>
      <div style={{ border: '1px solid var(--hb-line)', borderRadius: 12, marginTop: 12, padding: '13px 16px', display: 'flex', flexDirection: 'column', gap: 7, maxWidth: 460 }}>
        {[['Assessable profits', 'HKD 1,140,000'], ['Tax at 8.25% / 16.5% (two-tier)', 'HKD 122,100'], ['Provisional tax credit', '(HKD 48,300)'], ['Estimated tax payable', 'HKD 73,800']].map(([l, v], i) => (
          <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: i === 3 ? 700 : 400, borderTop: i === 3 ? '1px solid var(--hb-line)' : 'none', paddingTop: i === 3 ? 7 : 0 }}>
            <span style={{ color: i === 3 ? 'var(--hb-ink)' : 'var(--hb-muted)' }}>{l}</span>
            <span className="hb-num">{v}</span>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, flexWrap: 'wrap' }}>
        <button className="hb-btn" onClick={onSign} style={{ height: 44, fontSize: 14 }}>
          <HIcon name="pen" size={15} color="#fff" /> Sign electronically
        </button>
        <button className="hb-btn ghost" style={{ height: 44 }}>View full form</button>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--hb-faint)', marginTop: 10 }}>Signing authorises Atlas Ledger to submit to the IRD on your behalf.</div>
    </div>
  );
}

function ConfirmBody({ locked, missing, onConfirm }) {
  if (locked) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: 'var(--hb-muted)' }}>
        <HIcon name="lock" size={16} color="var(--hb-faint)" />
        Answer the {missing} open {missing === 1 ? 'question' : 'questions'} above first — then this becomes a one-tap confirm.
      </div>
    );
  }
  return (
    <div>
      <div style={{ border: '1px solid var(--hb-line)', borderRadius: 12, padding: '13px 16px', maxWidth: 460 }}>
        {[['Revenue', '380,000'], ['Total expenses', '(285,000)'], ['Net profit', '95,000'], ['Closing cash', '1,245,300']].map(([l, v], i) => (
          <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', fontSize: 13.5, fontWeight: i === 2 ? 700 : 400, borderTop: i === 2 ? '1px solid var(--hb-line)' : 'none' }}>
            <span style={{ color: i === 2 ? 'var(--hb-ink)' : 'var(--hb-muted)' }}>{l}</span>
            <span className="hb-num" style={{ fontSize: i === 2 ? 15 : 13.5 }}>{v}</span>
          </div>
        ))}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
          <HIcon name="checks" size={14} color="var(--hb-green)" />
          <span style={{ fontSize: 11.5, color: 'var(--hb-green)' }}>All 98 bank lines reconciled · clarifications answered</span>
        </div>
      </div>
      <button className="hb-btn" onClick={onConfirm} style={{ height: 46, fontSize: 14.5, marginTop: 14, padding: '0 26px' }}>Confirm May accounts</button>
      <div style={{ fontSize: 11.5, color: 'var(--hb-faint)', marginTop: 8 }}>May locks and files once confirmed. Your team is notified instantly.</div>
    </div>
  );
}

/* ── task list page ── */

function TasksPage({ state, setState, go }) {
  const { answers, signed, confirmed } = state;
  const answeredCount = (answers.q1 ? 1 : 0) + (answers.q2 ? 1 : 0);
  const confirmLocked = answeredCount < 2;

  const tasks = [
    { id: 'q1', kind: 'Answer', title: 'What was the HKD 52,000 transfer on 15 May?', meta: 'To WK Logistics · no matching document', done: !!answers.q1, doneNote: answers.q1 },
    { id: 'q2', kind: 'Answer', title: 'ATM withdrawal of HKD 8,000 on 6 May — what for?', meta: 'No matching document', done: !!answers.q2, doneNote: answers.q2 },
    { id: 'sign', kind: 'Sign', title: 'BIR51 Profits Tax Return', meta: 'Due 30 Jun · prepared by your team', done: signed, doneNote: 'Signed · submitted to IRD' },
    { id: 'confirm', kind: 'Confirm', title: 'Confirm May accounts', meta: confirmLocked ? 'Needs the 2 answers above' : 'Everything is ready — one tap', done: confirmed, doneNote: 'May closed & filed', locked: confirmLocked },
  ];
  const open = tasks.filter((t) => !t.done).length;
  const firstOpen = tasks.find((t) => !t.done && !t.locked);
  const [expanded, setExpanded] = React.useState(firstOpen ? firstOpen.id : null);

  const toggle = (id) => setExpanded(expanded === id ? null : id);
  const afterDone = (id) => {
    /* keep the user moving without forcing order: open the next open task, if any */
    const order = ['q1', 'q2', 'sign', 'confirm'];
    const next = tasks.find((t) => t.id !== id && !t.done && !(t.id === 'confirm' && answeredCount + 1 < 2) && order.indexOf(t.id) > -1);
    setExpanded(next ? next.id : null);
  };

  return (
    <div className="hb-page" style={{ width: 'min(720px, calc(100vw - 40px))', margin: '0 auto', paddingTop: 26, paddingBottom: 48 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', flexWrap: 'wrap', gap: 8 }}>
        <span style={{ fontSize: 22, fontWeight: 700 }}>Tasks</span>
        <span style={{ fontSize: 13, color: 'var(--hb-muted)', marginLeft: 10 }}>
          {confirmed ? 'All done for May ✓' : open + ' open · ~2 minutes total · any order you like'}
        </span>
      </div>

      {confirmed && (
        <div style={{ background: 'var(--hb-green-tint)', borderRadius: 12, padding: '14px 18px', marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
          <HIcon name="check" size={20} color="var(--hb-green)" sw={2.2} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700 }}>May is closed.</div>
            <div style={{ fontSize: 12.5, color: 'var(--hb-muted)', marginTop: 1 }}>Reports are updated and the BIR51 is on its way to the IRD.</div>
          </div>
          <button className="hb-btn ghost" onClick={() => go('reports')} style={{ whiteSpace: 'nowrap' }}>See May reports</button>
        </div>
      )}

      <div style={{ marginTop: 14, background: '#fff', border: '1px solid var(--hb-line)', borderRadius: 16, overflow: 'hidden' }}>
        {tasks.map((t, i) => {
          const isOpen = expanded === t.id && !t.done;
          return (
            <div key={t.id} style={{ borderTop: i === 0 ? 'none' : '1px solid var(--hb-line)' }}>
              {/* row header */}
              <div onClick={() => !t.done && toggle(t.id)} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '15px 20px',
                cursor: t.done ? 'default' : 'pointer',
                background: isOpen ? 'var(--hb-bg)' : '#fff',
                opacity: t.locked && !t.done ? 0.6 : 1, transition: 'background .15s',
              }}>
                {t.done
                  ? <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--hb-green-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><HIcon name="check" size={13} color="var(--hb-green)" sw={2.4} /></span>
                  : t.locked
                    ? <span style={{ width: 22, height: 22, borderRadius: '50%', border: '1.5px dashed var(--hb-faint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><HIcon name="lock" size={11} color="var(--hb-faint)" /></span>
                    : <span style={{ width: 22, height: 22, borderRadius: '50%', border: '1.5px solid var(--hb-line)', flexShrink: 0 }}></span>}
                <span className={'hb-tag ' + t.kind.toLowerCase()}>{t.kind}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600, color: t.done ? 'var(--hb-faint)' : 'var(--hb-ink)', textDecoration: t.done ? 'line-through' : 'none' }}>{t.title}</div>
                  <div style={{ fontSize: 12, color: t.done ? 'var(--hb-green)' : 'var(--hb-muted)', marginTop: 2 }}>{t.done ? t.doneNote : t.meta}</div>
                </div>
                {!t.done && <HIcon name="chevD" size={16} color="var(--hb-faint)" style={{ transform: isOpen ? 'rotate(180deg)' : 'none', transition: 'transform .15s', flexShrink: 0 }} />}
              </div>
              {/* expanded body */}
              {isOpen && (
                <div className="hb-page" style={{ padding: '6px 20px 22px 56px', background: 'var(--hb-bg)' }}>
                  {t.id === 'q1' || t.id === 'q2' ? (
                    <QuestionBody def={CLOSE_QUESTIONS.find((q) => q.id === t.id)} go={go}
                      onCommit={(val) => { setState((s) => ({ ...s, answers: { ...s.answers, [t.id]: val } })); afterDone(t.id); }} />
                  ) : t.id === 'sign' ? (
                    <SignBody onSign={() => { setState((s) => ({ ...s, signed: true })); afterDone('sign'); }} />
                  ) : (
                    <ConfirmBody locked={confirmLocked} missing={2 - answeredCount}
                      onConfirm={() => { setState((s) => ({ ...s, confirmed: true })); setExpanded(null); }} />
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div style={{ fontSize: 12.5, color: 'var(--hb-faint)', marginTop: 14, lineHeight: 1.6 }}>
        Tasks arrive here as your team needs them — answer in any order, anytime. Anything left unanswered is followed up by your team; nothing is ever auto-confirmed silently.
      </div>
    </div>
  );
}

Object.assign(window, { TasksPage });
