/* Truong So CRM — Deal Details (editable record) */
const { useState: useDS, useEffect: useDE, useRef: useDR } = React;

/* ---- inline editable field ---- */
function EditRow({ label, value, display, type = "text", options, placeholder, onSave, icon }) {
  const [editing, setEditing] = useDS(false);
  const [v, setV] = useDS(value ?? "");
  const ref = useDR(null);
  useDE(() => { if (editing && ref.current) { ref.current.focus(); if (ref.current.select) ref.current.select(); } }, [editing]);
  useDE(() => { setV(value ?? ""); }, [value]);

  function commit() { setEditing(false); if (v !== value) onSave(v); }
  function cancel() { setV(value ?? ""); setEditing(false); }

  return (
    <div className="editRow">
      <div className="erLabel">{icon}{label}</div>
      {!editing ? (
        <button className={"erValue" + (!display && !value ? " empty" : "")} onClick={() => setEditing(true)}>
          {display ?? (value || placeholder || "Thêm…")}
          <svg className="erPen" viewBox="0 0 24 24" width="13" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4z"/></svg>
        </button>
      ) : type === "select" ? (
        <select className="erInput" ref={ref} value={v} onChange={e => setV(e.target.value)} onBlur={commit}
          onKeyDown={e => { if (e.key === "Escape") cancel(); }}>
          {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      ) : (
        <input className="erInput" ref={ref} type={type === "date" ? "date" : "text"} value={v}
          inputMode={type === "currency" ? "numeric" : undefined}
          onChange={e => setV(type === "currency" ? e.target.value.replace(/\D/g, "") : e.target.value)}
          onBlur={commit} onKeyDown={e => { if (e.key === "Enter") commit(); if (e.key === "Escape") cancel(); }} />
      )}
    </div>
  );
}

const ACT_TYPES = [
  { id: "call", name: "Gọi điện", hue: 145, path: "M5 4h4l2 5-3 2a11 11 0 005 5l2-3 5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z" },
  { id: "meet", name: "Cuộc họp", hue: 262, path: "M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM23 21v-2a4 4 0 00-3-3.9M16 3.1a4 4 0 010 7.8" },
  { id: "task", name: "Công việc", hue: 215, path: "M9 11l3 3L22 4M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" },
  { id: "email", name: "Email", hue: 25, path: "M3 6h18v12H3zM3 7l9 6 9-6" },
  { id: "note", name: "Ghi chú", hue: 60, path: "M14 3v5h5M14 3l5 5v11a1 1 0 01-1 1H6a1 1 0 01-1-1V4a1 1 0 011-1zM8 13h8M8 17h6" },
];
function actMeta(id) { return ACT_TYPES.find(a => a.id === id) || ACT_TYPES[4]; }

function ActIcon({ id, size = 32 }) {
  const m = actMeta(id);
  return (
    <span className="actIcon" style={{ width: size, height: size, background: `oklch(0.95 0.045 ${m.hue})`, color: `oklch(0.5 0.14 ${m.hue})` }}>
      <svg viewBox="0 0 24 24" width={size * 0.5} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d={m.path}/></svg>
    </span>
  );
}

function ActivityComposer({ onAdd }) {
  const [type, setType] = useDS("call");
  const [subject, setSubject] = useDS("");
  const [due, setDue] = useDS("");
  const [note, setNote] = useDS("");
  const [mode, setMode] = useDS("plan"); // plan | log

  function submit() {
    if (!subject.trim()) return;
    onAdd({ id: "a" + Date.now(), type, subject: subject.trim(), due, note: note.trim(), done: mode === "log", logged: mode === "log" });
    setSubject(""); setDue(""); setNote("");
  }

  return (
    <div className="composer">
      <div className="compTypes">
        {ACT_TYPES.map(a => (
          <button key={a.id} className={"compType" + (type === a.id ? " on" : "")} style={{ "--h": a.hue }} onClick={() => setType(a.id)}>
            <svg viewBox="0 0 24 24" width="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d={a.path}/></svg>
            {a.name}
          </button>
        ))}
      </div>
      <input className="compSubject" placeholder={"Tiêu đề " + actMeta(type).name.toLowerCase() + "…"} value={subject}
        onChange={e => setSubject(e.target.value)} onKeyDown={e => { if (e.key === "Enter") submit(); }} />
      <textarea className="compNote" rows="2" placeholder="Ghi chú nội dung, kết quả trao đổi…" value={note} onChange={e => setNote(e.target.value)}></textarea>
      <div className="compFoot">
        <div className="compMode">
          <button className={"modeBtn" + (mode === "plan" ? " on" : "")} onClick={() => setMode("plan")}>Lên lịch</button>
          <button className={"modeBtn" + (mode === "log" ? " on" : "")} onClick={() => setMode("log")}>Đã xong</button>
        </div>
        {mode === "plan" && <input className="compDue" type="date" value={due} onChange={e => setDue(e.target.value)} />}
        <button className="btn primary compSave" onClick={submit} disabled={!subject.trim()}>
          {mode === "plan" ? "Lên lịch" : "Ghi nhận"}
        </button>
      </div>
    </div>
  );
}

function DealDetail({ deal, stages, pipeline, owners, onClose, onUpdate, onWin, onLose }) {
  const [activities, setActivities] = useDS([]);
  const [tab, setTab] = useDS("activity");
  useDE(() => {
    if (!deal) return;
    setActivities([
      { id: "seed2", type: "email", subject: "Gửi hồ sơ năng lực & báo giá sơ bộ", note: "Khách phản hồi quan tâm gói tiêu chuẩn.", when: "Hôm qua, 16:40", who: "u1", done: true, logged: true },
      { id: "seed1", type: "note", subject: "Khởi tạo cơ hội trong pipeline", note: "", when: "3 ngày trước", who: "u1", done: true, logged: true },
    ]);
  }, [deal && deal.id]);

  if (!deal) return null;
  const owner = ownerById(deal.owner);
  const stageIdx = stages.findIndex(s => s.id === deal.stage);
  const ownerOpts = owners.map(o => ({ value: o.id, label: o.name }));
  const labelOpts = [{ value: "", label: "Không có nhãn" }, ...Object.entries(window.CRM_LABELS).map(([k, v]) => ({ value: k, label: v.name }))];
  const closeDate = deal.next ? new Date(deal.next).toISOString().slice(0, 10) : "";

  function addActivity(a) {
    const when = a.logged ? "Vừa xong" : (a.due ? "Hẹn " + new Date(a.due).toLocaleDateString("vi-VN") : "Chưa định ngày");
    setActivities(prev => [{ ...a, when, who: deal.owner }, ...prev]);
  }
  function toggleDone(id) { setActivities(prev => prev.map(x => x.id === id ? { ...x, done: !x.done } : x)); }

  const pending = activities.filter(a => !a.done);
  const doneActs = activities.filter(a => a.done);

  return (
    <>
      <div className="drawerScrim" onClick={onClose}></div>
      <div className="record" role="dialog">
        <div className="recHead">
          <div className="recCrumb">
            <span>{pipeline.name}</span>
            <svg viewBox="0 0 24 24" width="14" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6"/></svg>
            <span className="recCrumbStage" style={{ color: `oklch(0.45 0.13 ${stages[stageIdx].hue})` }}>{window.tStage(stages[stageIdx])}</span>
          </div>
          <div className="recHeadRight">
            <button className="btn win sm" onClick={() => onWin(deal)}>{t("dd_win")}</button>
            <button className="btn lose sm" onClick={() => onLose(deal)}>{t("dd_lose")}</button>
            <button className="iconBtn" onClick={onClose} aria-label="Đóng">✕</button>
          </div>
        </div>

        <div className="recTitleWrap">
          <EditRow label="" value={deal.title} onSave={v => onUpdate({ title: v })}
            display={<span className="recTitle">{deal.title}</span>} />
        </div>

        <div className="stageFlow">
          {stages.map((s, i) => (
            <button key={s.id} className={"stageStep" + (i === stageIdx ? " current" : "") + (i < stageIdx ? " past" : "")}
              style={{ "--h": s.hue }} onClick={() => onUpdate({ stage: s.id })}>
              <span className="ssName">{window.tStage(s)}</span>
            </button>
          ))}
        </div>

        <div className="recBody">
          <aside className="recRail">
            <div className="railCard">
              <div className="railValue">{fmtVNDfull(deal.value)}</div>
              <div className="railValueLbl">{t("deal_value_label")}</div>
            </div>
            <div className="railSection">{t("rail_deal_info")}</div>
            <EditRow label={t("f_value")} type="currency" value={deal.value}
              display={fmtVNDfull(deal.value)} onSave={v => onUpdate({ value: Number(v) || 0 })} />
            <EditRow label={t("f_owner")} type="select" value={deal.owner} options={ownerOpts}
              display={<span className="erOwner"><Avatar owner={owner} size={20} />{owner.name}</span>}
              onSave={v => onUpdate({ owner: v })} />
            <EditRow label={t("f_stage")} type="select" value={deal.stage} options={stages.map(s => ({ value: s.id, label: window.tStage(s) }))}
              display={window.tStage(stages[stageIdx])} onSave={v => onUpdate({ stage: v })} />
            <EditRow label={t("f_label")} type="select" value={deal.label || ""} options={labelOpts}
              display={deal.label ? <Label id={deal.label} /> : null} placeholder="—" onSave={v => onUpdate({ label: v || null })} />
            <EditRow label={t("f_close")} type="date" value={closeDate}
              display={deal.next ? new Date(deal.next).toLocaleDateString("vi-VN") : null} placeholder="—"
              onSave={v => onUpdate({ next: v ? new Date(v).toISOString() : deal.next })} />

            <div className="railSection">{t("rail_contact_org")}</div>
            <EditRow label={t("f_org")} value={deal.company} onSave={v => onUpdate({ company: v })} />
            <EditRow label={t("f_person")} value={deal.person} placeholder="—" onSave={v => onUpdate({ person: v })} />
            <EditRow label={t("f_email")} value={deal.email} placeholder="—" onSave={v => onUpdate({ email: v })} />
            <EditRow label={t("f_phone")} value={deal.phone} placeholder="—" onSave={v => onUpdate({ phone: v })} />
            <EditRow label={t("f_source")} type="select" value={deal.source || "Website"}
              options={window.CRM_SOURCES.map(s => ({ value: s, label: s }))} display={deal.source || "Website"} onSave={v => onUpdate({ source: v })} />

            <div className="railSection">{t("rail_related")}</div>
            <PeopleList deal={deal} />

            <div className="railMeta">
              <div>Tạo lúc · 3 ngày trước</div>
              <div>Cập nhật · hôm nay bởi {owner.name}</div>
            </div>
          </aside>

          <main className="recMain">
            <div className="recTabs">
              {[["activity",t("tab_activity")],["products",t("tab_products")],["notes",t("tab_notes")],["files",t("tab_files")]].map(([id,name]) => (
                <button key={id} className={"recTab" + (tab === id ? " on" : "")} onClick={() => setTab(id)}>{name}</button>
              ))}
            </div>

            {tab === "activity" && (
            <div className="tabPane">
            <ActivityComposer onAdd={addActivity} />

            {pending.length > 0 && (
              <div className="feedGroup">
                <div className="feedHead">Sắp tới <span className="feedCount">{pending.length}</span></div>
                {pending.map(a => (
                  <div key={a.id} className="feedItem pending">
                    <button className="feedCheck" onClick={() => toggleDone(a.id)} aria-label="Đánh dấu xong"></button>
                    <ActIcon id={a.type} />
                    <div className="feedBody">
                      <div className="feedSubject">{a.subject}</div>
                      {a.note && <div className="feedNote">{a.note}</div>}
                      <div className="feedMeta"><span className="feedWhen due">{a.when}</span> · {ownerById(a.who).name}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div className="feedGroup">
              <div className="feedHead">Lịch sử hoạt động</div>
              {doneActs.length === 0 && <div className="feedEmpty">Chưa có hoạt động nào được ghi nhận.</div>}
              {doneActs.map(a => (
                <div key={a.id} className="feedItem">
                  <button className="feedCheck done" onClick={() => toggleDone(a.id)} aria-label="Bỏ đánh dấu">✓</button>
                  <ActIcon id={a.type} />
                  <div className="feedBody">
                    <div className="feedSubject">{a.subject}</div>
                    {a.note && <div className="feedNote">{a.note}</div>}
                    <div className="feedMeta"><span className="feedWhen">{a.when}</span> · {ownerById(a.who).name}</div>
                  </div>
                </div>
              ))}
            </div>
            </div>
            )}

            {tab === "products" && <ProductsTab onApplyTotal={(tot) => onUpdate({ value: tot })} />}
            {tab === "notes" && <NotesTab />}
            {tab === "files" && <FilesTab />}
          </main>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { DealDetail, EditRow, ActivityComposer });
