// Today screen — recruiter's morning action queue.
// Each card answers: who to contact, why, and what's the next move.

const { useI18n } = window.I18N;
const { Avatar, ScoreRing } = window.UI;

const Icon = window.Icon;

// === Urgency definitions ===
const URGENCY = {
  now:   { tone: "rose",   label: "now",   icon: "phone"     },
  high:  { tone: "amber",  label: "high",  icon: "sparkles"  },
  stale: { tone: "amber2", label: "stale", icon: "history"   },
  info:  { tone: "muted",  label: "info",  icon: "shield"    },
};

const KIND_ICONS = {
  scheduledCall:     "phone",
  interviewToday:    "users",
  replied:           "message",
  topFitNew:         "sparkles",
  noResponse:        "history",
  shortlistDecision: "check",
  consentExpiring:   "shield",
};

// === Toast ===
const Toast = ({ message, action, onAction, onClose }) => {
  React.useEffect(() => {
    const id = setTimeout(onClose, 4500);
    return () => clearTimeout(id);
  }, [message, onClose]);
  return (
    <div className="today-toast">
      <span>{message}</span>
      {action && (
        <button className="today-toast-btn" onClick={onAction}>{action}</button>
      )}
    </div>
  );
};

// === Action card ===
const ActionCard = ({ action, candidate, position, onOpen, onDone, onSnooze }) => {
  const { t, lang } = useI18n();
  const u = URGENCY[action.urgency];
  const kindIcon = KIND_ICONS[action.kind] || "sparkles";
  const kindLabel = t.today.kinds[action.kind] || action.kind;

  const labelFor = (k) => t.today.actions[k] || k;

  // Translate why-text for Thai using lookup table for known canned strings
  const whyText = action.why;
  const titleText = action.title;

  const score = candidate?.score;
  const scoreTone =
    score == null ? null :
    score >= 80 ? "good" :
    score >= 60 ? "ok"   : "weak";

  const handlePrimary = () => {
    if (action.primaryAction === "openProfile" || action.primaryAction === "review" ||
        action.primaryAction === "openPrep" || action.primaryAction === "reachOut" ||
        action.primaryAction === "shortlist") {
      onOpen("candidate", action.candidateId);
    } else {
      onDone(action.id, t.today.doneToast);
    }
  };

  return (
    <div className={"today-card today-card-" + u.tone}>
      <div className={"today-card-rail today-rail-" + u.tone}/>
      <div className="today-card-body">
        <div className="today-card-head">
          <div className="today-card-kind">
            <span className={"today-kind-icon today-kind-" + u.tone}>
              <Icon name={kindIcon} size={13}/>
            </span>
            <span className="today-kind-label">{kindLabel}</span>
            {action.when && (
              <span className="today-kind-when">
                <Icon name="clock" size={12}/>
                <span>{action.when}</span>
                {action.whenLabel && <span className="today-kind-whenSub">· {action.whenLabel}</span>}
              </span>
            )}
            {!action.when && action.whenLabel && (
              <span className="today-kind-whenSub">· {action.whenLabel}</span>
            )}
          </div>
          {action.pinned && (
            <span className="today-pin">
              <Icon name="bookmark" size={11}/>
              <span>Pinned</span>
            </span>
          )}
        </div>

        <div className="today-card-main">
          {candidate && (
            <div className="today-card-avatar-wrap">
              <Avatar name={candidate.name} size={44}/>
              {scoreTone && (
                <span className={"today-score-pill today-score-" + scoreTone}>{score}</span>
              )}
            </div>
          )}
          <div className="today-card-content">
            <button
              className="today-card-title"
              onClick={() => onOpen("candidate", action.candidateId)}
              title={titleText}
            >
              {titleText}
            </button>
            <p className="today-card-why">{whyText}</p>
            {position && (
              <div className="today-card-meta">
                <Icon name="briefcase" size={11}/>
                <span>{position.title}</span>
                <span className="today-meta-dot">·</span>
                <span>{position.location}</span>
              </div>
            )}
          </div>
        </div>

        <div className="today-card-actions">
          <button className={"btn btn-primary today-btn-primary"} onClick={handlePrimary}>
            {labelFor(action.primaryAction)}
          </button>
          {action.secondaryActions.map(k => (
            <button
              key={k}
              className="btn btn-ghost today-btn-secondary"
              onClick={() => {
                if (k === "openProfile") onOpen("candidate", action.candidateId);
                else onDone(action.id, t.today.doneToast);
              }}
            >
              {labelFor(k)}
            </button>
          ))}
          <span className="today-card-spacer"/>
          <button
            className="today-icon-btn"
            title={t.today.actions.snooze}
            onClick={() => onSnooze(action.id, t.today.snoozedToast)}
          >
            <Icon name="clock" size={14}/>
          </button>
          <button
            className="today-icon-btn"
            title={t.today.actions.markDone}
            onClick={() => onDone(action.id, t.today.doneToast)}
          >
            <Icon name="check" size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
};

// === Section ===
const Section = ({ id, title, sub, count, items, candidates, positions, onOpen, onDone, onSnooze }) => {
  if (items.length === 0) return null;
  const u = URGENCY[id];
  return (
    <section className="today-section">
      <header className="today-section-head">
        <span className={"today-section-dot today-rail-" + u.tone}/>
        <h2 className="today-section-title">{title}</h2>
        <span className="today-section-count">{count}</span>
        <p className="today-section-sub">{sub}</p>
      </header>
      <div className="today-section-cards">
        {items.map(action => (
          <ActionCard
            key={action.id}
            action={action}
            candidate={candidates.find(c => c.id === action.candidateId)}
            position={positions.find(p => p.id === action.positionId)}
            onOpen={onOpen}
            onDone={onDone}
            onSnooze={onSnooze}
          />
        ))}
      </div>
    </section>
  );
};

// === Today screen ===
const TodayScreen = ({ actions, candidates, positions, onOpen }) => {
  const { t } = useI18n();
  const [dismissed, setDismissed] = React.useState({}); // {id: 'done'|'snoozed'}
  const [toast, setToast] = React.useState(null);
  const [history, setHistory] = React.useState([]); // for undo

  const handleDone = (id, msg) => {
    setDismissed(d => ({ ...d, [id]: "done" }));
    setHistory(h => [...h, { id, kind: "done" }]);
    setToast({ message: msg, action: t.today.undo, onAction: () => undo(id) });
  };
  const handleSnooze = (id, msg) => {
    setDismissed(d => ({ ...d, [id]: "snoozed" }));
    setHistory(h => [...h, { id, kind: "snoozed" }]);
    setToast({ message: msg, action: t.today.undo, onAction: () => undo(id) });
  };
  const undo = (id) => {
    setDismissed(d => {
      const n = { ...d };
      delete n[id];
      return n;
    });
    setToast(null);
  };

  const visible = actions.filter(a => !dismissed[a.id]);
  const grouped = {
    now:   visible.filter(a => a.urgency === "now"),
    high:  visible.filter(a => a.urgency === "high"),
    stale: visible.filter(a => a.urgency === "stale"),
    info:  visible.filter(a => a.urgency === "info"),
  };

  const totalLeft = visible.length;
  const completed = actions.length - totalLeft;
  const progressPct = (completed / actions.length) * 100;

  return (
    <div className="fade-in today-screen">
      <div className="page-head today-head">
        <div>
          <div className="page-eyebrow">{t.today.eyebrow}</div>
          <h1 className="page-title">{t.today.title}</h1>
          <p className="page-sub">{t.today.sub}</p>
        </div>
        <div className="today-progress-card">
          <div className="today-progress-head">
            <div className="today-progress-num">{totalLeft}</div>
            <div className="today-progress-label">remaining</div>
          </div>
          <div className="today-progress-bar">
            <div className="today-progress-fill" style={{ width: progressPct + "%" }}/>
          </div>
          <div className="today-progress-foot">
            <span>{completed} done</span>
            <span>{actions.length} total</span>
          </div>
        </div>
      </div>

      {totalLeft === 0 && (
        <div className="today-empty">
          <div className="today-empty-icon">
            <Icon name="check" size={32}/>
          </div>
          <h3 className="today-empty-title">{t.today.empty}</h3>
        </div>
      )}

      <Section id="now"   title={t.today.now}   sub={t.today.nowSub}   count={grouped.now.length}
        items={grouped.now}   candidates={candidates} positions={positions}
        onOpen={onOpen} onDone={handleDone} onSnooze={handleSnooze}/>
      <Section id="high"  title={t.today.high}  sub={t.today.highSub}  count={grouped.high.length}
        items={grouped.high}  candidates={candidates} positions={positions}
        onOpen={onOpen} onDone={handleDone} onSnooze={handleSnooze}/>
      <Section id="stale" title={t.today.stale} sub={t.today.staleSub} count={grouped.stale.length}
        items={grouped.stale} candidates={candidates} positions={positions}
        onOpen={onOpen} onDone={handleDone} onSnooze={handleSnooze}/>
      <Section id="info"  title={t.today.info}  sub={t.today.infoSub}  count={grouped.info.length}
        items={grouped.info}  candidates={candidates} positions={positions}
        onOpen={onOpen} onDone={handleDone} onSnooze={handleSnooze}/>

      {toast && (
        <Toast {...toast} onClose={() => setToast(null)}/>
      )}
    </div>
  );
};

window.SCREENS_F = { TodayScreen };
