/* ============================================================
   VLF 2026 · OPS HUB — Tổng quan (role-aware)
   BTC: trung tâm chỉ huy. TNV: trung tâm ca trực.
   ============================================================ */
const OPS_NOW = '06:18';
const toMin = (hm) => { const [h, m] = String(hm).split(':').map(Number); return h * 60 + (m || 0); };

function nowBlocks(ros) {
  const n = toMin(OPS_NOW);
  // mốc "đang diễn ra" = mốc gần nhất đã tới giờ (tm <= bây giờ)
  let idx = -1;
  ros.forEach((b, i) => { if (toMin(b.tm) <= n) idx = i; });
  if (idx === -1) idx = 0;
  return { idx };
}

function OpsHub({ nav, role, isBtc, phase, store }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const team = O.teamForRole(role.id);
  const today = O.todayTasks();
  const myTeamTasks = today.filter((t) => t.team === team.id);
  const collabTasks = today.filter((t) => t.team !== team.id && (t.collab || []).includes(team.id));

  const openInc = O.incidentsForPhase().filter((i) => i.status !== 'resolved');
  const highInc = openInc.filter((i) => i.sev === 'high');
  const doneTeam = myTeamTasks.filter((t) => t.status === 'done').length;

  return isBtc
    ? <BtcHub {...{ nav, role, team, lang, O, openInc, highInc, phase, store }} />
    : <TnvHub {...{ nav, role, team, lang, O, myTeamTasks, collabTasks, doneTeam, phase, store }} />;
}

/* ---------------- BTC: trung tâm chỉ huy ---------------- */
function BtcHub({ nav, role, team, lang, O, openInc, highInc, phase, store }) {
  const todayT = O.todayTasks();
  const allDone = todayT.filter((t) => t.status === 'done').length;
  const hc = O.headTotal();
  const onDuty = hc.inn + '/' + hc.plan;
  const kpis = O.kpisFor(phase, { doneT: allDone, totalT: todayT.length, openInc: openInc.length, highInc: highInc.length, onDuty });

  return (
    <>
      <RoleCard role={role} team={team} lang={lang} isBtc />
      {store && <CheckinBanner store={store} nav={nav} team={team} role={role} />}
      <div className="ops-kpis">
        {kpis.map((s, i) => (
          <div className="v-card ops-kpi" key={i} onClick={s.go ? () => nav(s.go) : undefined} style={{ cursor: s.go ? 'pointer' : 'default' }}>
            <b style={{ color: s.tone }}>{s.v}</b>
            <div>{trL(lang, s.k)}</div>
            {s.warn && <span className="ops-kpi-dot" />}
          </div>
        ))}
      </div>

      <NowStrip nav={nav} lang={lang} O={O} />

      {phase === 'live' && <WeatherStrip O={O} lang={lang} nav={nav} />}
      {phase === 'live' && <HeadcountCard O={O} lang={lang} nav={nav} />}

      {phase === 'live' && highInc.length > 0 && (
        <>
          <SectionHead title={trL(lang, { vi: 'Sự cố cần chú ý', en: 'Incidents to watch' })} right={<a onClick={() => nav('coord')}>{trL(lang, { vi: 'Tất cả', en: 'All' })} ›</a>} />
          <div className="v-card">
            {highInc.map((inc) => <IncidentRow key={inc.id} inc={inc} lang={lang} onClick={() => nav('incident', { id: inc.id })} />)}
          </div>
        </>
      )}

      {phase === 'live' && <>
        <SectionHead title={trL(lang, { vi: 'Chờ phê duyệt khẩn', en: 'Urgent approval' })} />
        <ApprovalCard O={O} lang={lang} onMore={() => nav('coord')} />
      </>}

      <SectionHead title={trL(lang, { vi: 'Tiến độ các đội', en: 'Team progress' })} right={<a onClick={() => nav('tasks')}>{trL(lang, { vi: 'Bảng nhiệm vụ', en: 'Task board' })} ›</a>} />
      <div className="v-card ops-teamprog">
        {O.teams.filter((t) => todayT.some((x) => x.team === t.id)).map((t) => {
          const ts = todayT.filter((x) => x.team === t.id);
          const dn = ts.filter((x) => x.status === 'done').length;
          return (
            <div className="ops-tp-row" key={t.id} onClick={() => nav('tasks', { team: t.id })}>
              <span className="ops-tp-dot" style={{ background: t.color }} />
              <span className="ops-tp-name">{trL(lang, t.name)}</span>
              <ProgressBar value={dn} total={ts.length} tone={t.color} />
              <span className="ops-tp-n">{dn}/{ts.length}</span>
            </div>);
        })}
      </div>
    </>);
}

/* ---------------- TNV: trung tâm ca trực ---------------- */
function TnvHub({ nav, role, team, lang, O, myTeamTasks, collabTasks, doneTeam, phase, store }) {
  const [taken, setTaken] = useState({});
  const reqs = [
    { id: 'r1', q: { vi: 'Khách hỏi đường về cổng chính', en: 'Guest asks way to main gate' }, who: 'CSKH', at: '06:12' },
    { id: 'r2', q: { vi: 'Cần xe điện cho khách lớn tuổi', en: 'Cart needed for elderly guest' }, who: 'Shuttle', at: '06:09' },
  ];
  const shift = (window.VLF.staffRoleById(role.id).shift || '06:00–12:00').split('–');

  return (
    <>
      <RoleCard role={role} team={team} lang={lang} />
      {store && <CheckinBanner store={store} nav={nav} team={team} role={role} />}

      <OpsDutyBoard O={O} lang={lang} role={role} nav={nav} />

      <div className="v-card ops-shift">
        <div className="ops-shift-time">
          <b>{shift[0]}</b><span>{trL(lang, { vi: 'đến', en: 'to' })} {shift[1] || ''}</span>
        </div>
        <div className="ops-shift-mid">
          <div className="t">{trL(lang, team.zone || team.name)}</div>
          <div className="s">{trL(lang, { vi: 'Đội trưởng', en: 'Lead' })}: {team.lead} · 094 552 028</div>
          <div className="s">{trL(lang, { vi: 'Bộ đàm', en: 'Radio' })}: {team.radio}</div>
        </div>
        {store && store.shiftIn && !store.shiftOut
          ? <span className="ops-onduty"><i />{trL(lang, { vi: 'Đang trực', en: 'On duty' })}</span>
          : store && store.shiftOut
            ? <span className="v-tag" style={{ color: '#1F8A5B', background: 'rgba(31,138,91,.14)' }}>{trL(lang, { vi: 'Đã tan ca', en: 'Off duty' })}</span>
            : <span className="v-tag" style={{ color: 'var(--vlf-gold-700)', background: 'rgba(201,162,75,.16)' }}>{trL(lang, { vi: 'Chưa vào ca', en: 'Not in' })}</span>}
      </div>

      <div className="v-card ops-briefcard" onClick={() => nav('brief')}>
        <div className="ops-brief-ic"><Icon name="bell" size={18} sw={1.8} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="t">{trL(lang, { vi: 'Briefing sáng đã chốt', en: 'Morning briefing posted' })}</div>
          <div className="s">{O.briefing.tm} · {O.briefing.agenda.length} {trL(lang, { vi: 'điểm · chạm để xem', en: 'points · tap to view' })}</div>
        </div>
        <Icon name="chev" size={18} className="chev" />
      </div>

      <OpsWorklist O={O} lang={lang} team={team} tasks={myTeamTasks} collab={collabTasks} nav={nav} />

      <SectionHead title={trL(lang, { vi: 'Nhiệm vụ đội ' + trL(lang, team.name), en: trL(lang, team.name) + ' tasks' })}
        right={<span className="v-muted" style={{ fontSize: 12 }}>{doneTeam}/{myTeamTasks.length}</span>} />
      <div className="v-card">
        {myTeamTasks.map((t) => <TaskRow key={t.id} task={t} lang={lang} onClick={() => nav('task', { id: t.id })} />)}
        {myTeamTasks.length === 0 && <div className="v-row" style={{ cursor: 'default' }}><div className="v-muted" style={{ fontSize: 13 }}>{trL(lang, { vi: 'Chưa có nhiệm vụ cho đội bạn.', en: 'No tasks for your team yet.' })}</div></div>}
      </div>

      {collabTasks.length > 0 && (
        <>
          <SectionHead title={trL(lang, { vi: 'Đội bạn phối hợp', en: 'You’re collaborating on' })} />
          <div className="v-card">
            {collabTasks.map((t) => <TaskRow key={t.id} task={t} lang={lang} collab onClick={() => nav('task', { id: t.id })} />)}
          </div>
        </>
      )}

      {phase === 'live' && <>
      <SectionHead title={trL(lang, { vi: 'Yêu cầu hỗ trợ gần bạn', en: 'Support requests near you' })} />
      <div className="v-card">
        {reqs.map((rq) => (
          <div className="v-row" key={rq.id} style={{ cursor: 'default' }}>
            <div className="ops-reqic"><Icon name="pin" size={18} sw={1.7} /></div>
            <div style={{ flex: 1, minWidth: 0 }}><div className="t" style={{ fontSize: 13.5 }}>{trL(lang, rq.q)}</div><div className="s">{rq.who} · {rq.at}</div></div>
            <button className={'v-btn ' + (taken[rq.id] ? 'v-btn-ghost' : 'v-btn-primary')} style={{ width: 'auto', height: 34, padding: '0 13px', fontSize: 13 }} onClick={() => { const willTake = !taken[rq.id]; setTaken((s) => ({ ...s, [rq.id]: willTake })); if (willTake && store && store.commit) store.commit(trL(lang, { vi: 'Nhận hỗ trợ: ', en: 'Took: ' }) + trL(lang, rq.q)); }}>{taken[rq.id] ? trL(lang, { vi: 'Đã nhận', en: 'Taken' }) : trL(lang, { vi: 'Nhận', en: 'Take' })}</button>
          </div>
        ))}
      </div>
      </>}

      <div className="ops-quick">
        <button className="ops-quick-b" onClick={() => nav('coord', { report: true })}><Icon name="bell" size={19} sw={1.8} /><span>{trL(lang, { vi: 'Báo sự cố', en: 'Report issue' })}</span></button>
        <button className="ops-quick-b" onClick={() => nav('sop', { id: window.VLF.ops.sopForTeam(team.id) })}><Icon name="info" size={19} sw={1.8} /><span>{trL(lang, { vi: 'Sổ tay vị trí', en: 'My handbook' })}</span></button>
        <button className="ops-quick-b" onClick={() => nav('emg')}><Icon name="shield" size={19} sw={1.8} /><span>{trL(lang, { vi: 'Khẩn cấp', en: 'Emergency' })}</span></button>
      </div>
    </>);
}

/* ---------- shared cards ---------- */
function RoleCard({ role, team, lang, isBtc }) {
  return (
    <div className="v-card ops-rolecard">
      <OpsAva name={role.me} size={46} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="ops-rc-name">{role.me}</div>
        <div className="ops-rc-sub">{window.VLF.L(lang, role, 'name')}</div>
        <div className="ops-rc-team"><i style={{ background: team.color }} />{team.members.length} {trL(lang, { vi: 'thành viên', en: 'members' })} · {trL(lang, { vi: 'Bộ đàm', en: 'Radio' })} {team.radio}{team.role ? ' · ' + trL(lang, team.role) : ''}</div>
        {team.note && <div className="ops-rc-note"><Icon name="info" size={11} sw={2} />{trL(lang, team.note)}</div>}
      </div>
      <span className="v-tag" style={{ color: isBtc ? 'var(--vlf-purple-700)' : 'var(--vlf-gold-700)' }}>{isBtc ? 'BTC' : 'TNV'}</span>
    </div>);
}

function NowStrip({ nav, lang, O }) {
  const { idx } = nowBlocks(O.runOfShow);
  const win = O.runOfShow.slice(Math.max(0, idx - 1), idx + 3);
  return (
    <>
      <SectionHead title={trL(lang, { vi: 'Dòng vận hành hôm nay', en: 'Today’s run-of-show' })} sub={O.today + ' · ' + trL(lang, O.dayTheme)} />
      <div className="v-card ops-ros">
        {win.map((b, i) => {
          const tm = window.VLF.ops.teamById(b.team);
          const cur = O.runOfShow[idx] === b;
          return (
            <div className={'ops-ros-row' + (cur ? ' now' : '')} key={i}>
              <div className="ops-ros-time">{b.tm}{cur && <span className="ops-ros-live">{trL(lang, { vi: 'bây giờ', en: 'now' })}</span>}</div>
              <span className="ops-ros-dot" style={{ background: b.st === 'done' ? '#1F8A5B' : b.st === 'doing' ? 'var(--vlf-gold-500)' : tm.color }} />
              <div className="ops-ros-body">
                <div className="t">{trL(lang, b.t)}</div>
                <div className="s">{trL(lang, tm.name)}</div>
              </div>
              <StatusChip st={b.st} lang={lang} />
            </div>);
        })}
      </div>
    </>);
}

/* ---------- weather strip + headcount (BTC live) ---------- */
function WeatherStrip({ O, lang, nav }) {
  const w = O.weather; const m = O.weatherMeta[w.state];
  return (
    <div className="v-card ops-weather" style={{ borderColor: m.c, cursor: nav ? 'pointer' : 'default' }} onClick={nav ? () => nav('coord') : undefined}>
      <div className="ops-wx-main">
        <div className="ops-wx-temp">{w.temp}</div>
        <div className="ops-wx-mid">
          <span className="ops-wx-state" style={{ color: m.c, background: m.bg }}>{trL(lang, m)}</span>
          <div className="ops-wx-note">{trL(lang, w.note)}</div>
        </div>
        <div className="ops-wx-heat"><b>{w.heat}°</b><span>{trL(lang, { vi: 'cảm nhận', en: 'feels' })}</span></div>
      </div>
      <div className="ops-wx-foot"><Icon name="clock" size={13} sw={1.9} />{trL(lang, w.next)}<Icon name="chev" size={15} className="chev" style={{ marginLeft: 'auto' }} /></div>
    </div>);
}

function HeadcountCard({ O, lang, nav }) {
  const tot = O.headTotal();
  return (
    <>
      <SectionHead title={trL(lang, { vi: 'Quân số theo đội', en: 'Headcount by team' })}
        sub={trL(lang, { vi: 'Đã điểm danh / kế hoạch · mục tiêu 05:00', en: 'Checked-in / plan · target 05:00' })}
        right={<span className="v-pill" style={{ background: 'var(--vlf-purple-50)', color: 'var(--vlf-purple-700)' }}>{tot.inn}/{tot.plan}</span>} />
      <div className="v-card ops-headcount">
        {O.headcount.map((h) => {
          const tm = O.teamById(h.team); const short = h.plan - h.inn;
          return (
            <div className={'ops-hc-row' + (short >= 2 ? ' short' : '')} key={h.team} onClick={() => nav('tasks', { team: h.team })}>
              <span className="ops-hc-dot" style={{ background: tm.color }} />
              <span className="ops-hc-name">{trL(lang, tm.zone || tm.name)}</span>
              <ProgressBar value={h.inn} total={h.plan} tone={short >= 2 ? '#C0392B' : tm.color} />
              <span className="ops-hc-n" style={short >= 2 ? { color: '#C0392B' } : null}>{h.inn}/{h.plan}</span>
              {short >= 2 && <button className="ops-hc-call" onClick={(e) => { e.stopPropagation(); nav('coord'); }}>{trL(lang, { vi: 'Điều TNV', en: 'Add vols' })}</button>}
            </div>);
        })}
      </div>
    </>);
}

function IncidentRow({ inc, lang, onClick }) {
  return (
    <div className="v-row" onClick={onClick}>
      <div className="ops-inc-ic" style={{ background: window.VLF.ops.sevMeta[inc.sev].bg, color: window.VLF.ops.sevMeta[inc.sev].c }}><Icon name="bell" size={18} sw={1.8} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="t" style={{ fontSize: 13.5 }}>{trL(lang, inc.title)}</div>
        <div className="s">{trL(lang, inc.zone)} · {inc.at} · {trL(lang, window.VLF.ops.incStatus[inc.status])}</div>
      </div>
      <Icon name="chev" size={18} className="chev" />
    </div>);
}

function TaskRow({ task, lang, onClick, collab }) {
  const O = window.VLF.ops;
  const dn = task.steps.filter((s) => s.done).length;
  const info = O.deadlineInfo(task);
  return (
    <div className={'v-row ops-taskrow' + (info.state === 'overdue' ? ' ops-taskrow--late' : '')} onClick={onClick}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="ops-tr-top">
          <PrioChip p={task.prio} /><span className="ops-tr-win">{task.window}</span>
          {info.state === 'overdue' && <span className="ops-tr-late"><Icon name="bell" size={11} sw={2.2} />{trL(lang, { vi: 'TRỄ', en: 'LATE' })}</span>}
          {info.state === 'soon' && <span className="ops-tr-soon">{trL(lang, { vi: O.leftLabel(info, lang), en: O.leftLabel(info, lang) })}</span>}
          {collab && <span className="ops-tr-collab">{trL(lang, { vi: 'phối hợp', en: 'collab' })}</span>}
        </div>
        <div className="t" style={{ fontSize: 14 }}>{trL(lang, task.title)}</div>
        <div className="ops-tr-meta">
          <AvaStack names={task.assignees} size={22} max={3} />
          <span className="ops-tr-steps">{dn}/{task.steps.length} {trL(lang, { vi: 'việc', en: 'steps' })}</span>
          {(task.collab || []).length > 0 && <span className="ops-tr-coll"><Icon name="user" size={12} sw={2} />{(task.collab || []).length + 1} {trL(lang, { vi: 'đội', en: 'teams' })}</span>}
        </div>
      </div>
      <StatusChip st={task.status} lang={lang} />
    </div>);
}

function ApprovalCard({ O, lang, onMore }) {
  const [sign, setSign] = useState(0);
  const a = O.approval;
  return (
    <div className="v-card v-urgent" style={{ padding: 15 }}>
      <span className="v-pill" style={{ background: 'rgba(192,57,43,.12)', color: 'var(--vlf-under)' }}>{trL(lang, { vi: 'Khẩn · 2 chữ ký', en: 'Urgent · dual sign-off' })}</span>
      <div style={{ fontWeight: 700, fontSize: 15, margin: '10px 0 3px' }}>{trL(lang, a.title)}</div>
      <div className="v-muted" style={{ fontSize: 12.5, lineHeight: 1.45 }}>{trL(lang, a.body)}</div>
      <div className="v-muted" style={{ fontSize: 11.5, marginTop: 7 }}>{trL(lang, { vi: 'Đề xuất bởi', en: 'Raised by' })}: {a.by}</div>
      {sign === 0 && <div style={{ display: 'flex', gap: 10, marginTop: 13 }}><button className="v-btn v-btn-ghost" style={{ height: 44, fontSize: 14 }}>{trL(lang, { vi: 'Từ chối', en: 'Reject' })}</button><button className="v-btn v-ops-btn" style={{ height: 44, fontSize: 14 }} onClick={() => setSign(1)}>{trL(lang, { vi: 'Ký (1/2)', en: 'Sign (1/2)' })}</button></div>}
      {sign === 1 && <div style={{ marginTop: 13 }}><div className="v-muted" style={{ fontSize: 12, marginBottom: 9, display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={15} sw={2.6} style={{ color: '#1F8A5B' }} />{trL(lang, { vi: 'Chữ ký 1/2 · ' + (a.sign1 || 'Phạm Hoàng'), en: 'Signature 1/2 · ' + (a.sign1 || 'Phạm Hoàng') })}</div><button className="v-btn v-ops-btn" style={{ height: 44, fontSize: 14 }} onClick={() => setSign(2)}>{trL(lang, { vi: 'Duyệt cuối (2/2) · ' + (a.sign2 || '') + ' → đẩy', en: 'Final approve (2/2) → push' })}</button></div>}
      {sign === 2 && <div style={{ marginTop: 13, display: 'flex', alignItems: 'center', gap: 8, color: '#1F8A5B', fontWeight: 700, fontSize: 13.5 }}><Icon name="check" size={18} sw={2.6} />{trL(lang, { vi: 'Đã duyệt 2/2 · đã đẩy tới khách', en: 'Approved 2/2 · pushed' })}</div>}
    </div>);
}

Object.assign(window, { OpsHub, NowStrip, WeatherStrip, HeadcountCard, IncidentRow, TaskRow, ApprovalCard, RoleCard, OPS_NOW });
