// Segment sections (MD Services, Management, New Business, Internal)

function MDServicesSection({ onOpenClient, companies, onAddCompany, variant }){
  // Subscribe to store so company-edit overrides re-render the rows
  window.useStore(s => s.companyOverrides);
  const live = window.useLiveData ? window.useLiveData() : null;
  const fmt = window.fmtMoney || (n => "₪" + n);
  const totals = companies.reduce((acc, name) => {
    const b = window.findClientBookings ? window.findClientBookings(name, live) : null;
    if (b) {
      acc.booked += b.booked;
      acc.awaitingInvoice += b.awaitingInvoice;
      acc.late += b.late;
    }
    return acc;
  }, { booked: 0, awaitingInvoice: 0, late: 0 });
  return (
    <section id="md-services" className="section">
      <div className="section-head">
        <div className="title">
          <span className="eyebrow">Private retainer · White-glove</span>
          <h2>MD <em>Service</em> companies</h2>
        </div>
        <div className="meta">
          <span><b>{companies.length}</b> Active</span>
          <span><b>{live ? fmt(totals.booked) : "—"}</b> Booked '26</span>
          <span><b>{live ? fmt(totals.awaitingInvoice) : "—"}</b> Awaiting invoice</span>
        </div>
      </div>
      <div className="rows gap-l">
        {companies.map((name) => {
          const d = MD_DATA[name];
          if(!d) return null;
          return (
            <CompanyRow
              key={name}
              variant={variant}
              name={name}
              segment="md"
              data={d}
              onOpen={() => onOpenClient({ ...d, name, segment:"md", segmentLabel:"MD Service" })}
            />
          );
        })}
        <button className="add-row" onClick={()=>onAddCompany("md")}>
          <span className="plus">+</span> Add MD Service client
        </button>
      </div>
    </section>
  );
}

function ManagementSection({ onOpenClient, companies, onAddCompany, variant }){
  window.useStore(s => s.companyOverrides);
  const live = window.useLiveData ? window.useLiveData() : null;
  const fmt = window.fmtMoney || (n => "₪" + n);
  const totals = companies.reduce((acc, name) => {
    const b = window.findClientBookings ? window.findClientBookings(name, live) : null;
    if (b) {
      acc.booked += b.booked;
      acc.awaitingInvoice += b.awaitingInvoice;
      acc.paid += b.paid;
    }
    return acc;
  }, { booked: 0, awaitingInvoice: 0, paid: 0 });
  return (
    <section id="management" className="section">
      <div className="section-head">
        <div className="title">
          <span className="eyebrow">Company-wide retainer · Benefits</span>
          <h2>Management <em>& Retainer</em></h2>
        </div>
        <div className="meta">
          <span><b>{companies.length}</b> Active</span>
          <span><b>{live ? fmt(totals.booked) : "—"}</b> Booked '26</span>
          <span><b>{live ? fmt(totals.paid) : "—"}</b> Paid</span>
        </div>
      </div>
      <div className="rows gap-l">
        {companies.map((name) => {
          const d = MGMT_DATA[name];
          if(!d) return null;
          return (
            <CompanyRow
              key={name}
              variant={variant}
              name={name}
              segment="mgmt"
              data={d}
              onOpen={() => onOpenClient({ ...d, name, segment:"mgmt", segmentLabel:"Management" })}
            />
          );
        })}
        <button className="add-row" onClick={()=>onAddCompany("mgmt")}>
          <span className="plus">+</span> Add Management client
        </button>
      </div>
    </section>
  );
}

function NewBusinessSection(){
  const monthOrder = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
  const monthFull = ["January","February","March","April","May","June","July","August","September","October","November","December"];

  // months we span in the data — find min/max
  const events = NEW_BIZ.map(e => ({...e, monthIdx: monthOrder.indexOf(e.month), dayN: parseInt(e.day)}));
  const months = [...new Set(events.map(e => e.monthIdx))].sort((a,b)=>a-b);
  // anchor first month (use 2026)
  const [cursor, setCursor] = React.useState(months[0]); // index into monthOrder
  const [selected, setSelected] = React.useState(null);

  const year = 2026;
  const firstWeekday = new Date(year, cursor, 1).getDay(); // 0=Sun
  // Mon-start: shift so Mon=0
  const offset = (firstWeekday + 6) % 7;
  const daysInMonth = new Date(year, cursor + 1, 0).getDate();
  const cells = [];
  for(let i=0; i<offset; i++) cells.push(null);
  for(let d=1; d<=daysInMonth; d++) cells.push(d);
  while(cells.length % 7 !== 0) cells.push(null);

  // events for current month
  const monthEvents = events.filter(e => e.monthIdx === cursor);
  const eventsByDay = {};
  monthEvents.forEach(e => {
    if(!eventsByDay[e.dayN]) eventsByDay[e.dayN] = [];
    eventsByDay[e.dayN].push(e);
  });

  const today = { m: 4, d: 4 }; // May 4, 2026
  const pipelineTotal = monthEvents.reduce((sum,e)=>{
    const m = e.value.match(/₪([\d.,]+)([KM])/);
    if(!m) return sum;
    const n = parseFloat(m[1].replace(",","")) * (m[2]==="M"?1000:1);
    return sum + n;
  }, 0);

  const stageColor = (s) => s==="hot"?"var(--accent)":s==="won"?"var(--green)":s==="prep"?"var(--plum)":"var(--gold)";

  const goPrev = () => {
    const prev = months.filter(m=>m<cursor).pop();
    if(prev !== undefined){ setCursor(prev); setSelected(null); }
  };
  const goNext = () => {
    const next = months.find(m=>m>cursor);
    if(next !== undefined){ setCursor(next); setSelected(null); }
  };

  return (
    <section id="new-business" className="section">
      <div className="section-head">
        <div className="title">
          <span className="eyebrow">One-time events · Kickoffs · Projects</span>
          <h2>New <em>business</em> · Calendar</h2>
        </div>
        <div className="meta">
          <span><b>{NEW_BIZ.length}</b> Upcoming</span>
          <span><b>₪695K</b> Pipeline</span>
          <span><b>3</b> Confirmed</span>
        </div>
      </div>

      <div className="nb-calendar">
        <div className="nb-cal-head">
          <button className="cal-nav" onClick={goPrev} disabled={!months.filter(m=>m<cursor).length}><Icon.ChevL/></button>
          <h3>{monthFull[cursor]} <span style={{color:"var(--ink-soft)",fontWeight:400}}>{year}</span></h3>
          <button className="cal-nav" onClick={goNext} disabled={!months.find(m=>m>cursor)}><Icon.ChevR/></button>
          <div className="nb-cal-stat">
            <span><b>{monthEvents.length}</b> events</span>
            <span><b>₪{Math.round(pipelineTotal)}K</b> in month</span>
          </div>
        </div>

        <div className="nb-cal-body">
          <div className="nb-cal-grid">
            {["MON","TUE","WED","THU","FRI","SAT","SUN"].map(d=>(
              <div key={d} className="cal-dow">{d}</div>
            ))}
            {cells.map((d, i) => {
              if(d === null) return <div key={i} className="cal-cell empty"/>;
              const evts = eventsByDay[d] || [];
              const isToday = cursor === today.m && d === today.d;
              const dow = new Date(year, cursor, d).getDay();
              const isWeekend = dow === 0 || dow === 6;
              const isSelected = selected === d;
              return (
                <div key={i}
                     className={"cal-cell " + (isToday?"today ":"") + (isWeekend?"weekend ":"") + (isSelected?"selected ":"") + (evts.length?"has-events ":"")}
                     onClick={()=> evts.length && setSelected(isSelected ? null : d)}>
                  <div className="cal-day">
                    <span className="cal-num">{d}</span>
                    {isToday && <span className="cal-mo">TODAY</span>}
                  </div>
                  <div className="cal-events">
                    {evts.slice(0,2).map((e, j)=>(
                      <div key={j} className={"cal-evt " + e.stage} style={{ borderLeftColor: stageColor(e.stage) }}>
                        <b>{e.client}</b>
                        <span>{e.title}</span>
                      </div>
                    ))}
                    {evts.length > 2 && <span className="cal-more">+{evts.length-2} more</span>}
                  </div>
                </div>
              );
            })}
          </div>

          <aside className="nb-cal-side">
            {selected !== null && eventsByDay[selected] ? (
              <React.Fragment>
                <div className="nb-side-head">
                  <div className="nb-side-date">
                    <span className="d">{selected}</span>
                    <span className="m">{monthFull[cursor]}</span>
                  </div>
                  <span className="nb-side-count">{eventsByDay[selected].length} event{eventsByDay[selected].length>1?"s":""}</span>
                </div>
                <div className="nb-side-list">
                  {eventsByDay[selected].map(e => (
                    <div key={e.id} className="nb-side-evt">
                      <div className="nb-side-evt-top">
                        <span className="sched-type">{e.type}</span>
                        <span className={"sched-stage " + e.stage}>{e.stageLabel}</span>
                      </div>
                      <h4>{e.title}</h4>
                      <div className="sched-meta">
                        <span><Icon.Users/> {e.headcount}</span>
                        <span><Icon.Pin/> {e.venue}</span>
                      </div>
                      <div className="nb-side-evt-foot">
                        <span className="value"><Icon.Money/> {e.value}</span>
                      </div>
                      <p>{e.note}</p>
                    </div>
                  ))}
                </div>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div className="nb-side-head">
                  <h4 style={{fontFamily:"Fraunces,serif",fontSize:18,letterSpacing:"-.02em"}}>This month</h4>
                  <span className="nb-side-count">{monthEvents.length}</span>
                </div>
                <div className="nb-side-list compact">
                  {monthEvents.sort((a,b)=>a.dayN-b.dayN).map(e => (
                    <div key={e.id} className="nb-side-evt mini" onClick={()=>setSelected(e.dayN)}>
                      <div className="nb-side-mini-date" style={{background: stageColor(e.stage)}}>
                        <span className="dd">{String(e.dayN).padStart(2,"0")}</span>
                        <span className="mm">{e.month}</span>
                      </div>
                      <div className="nb-side-mini-body">
                        <b>{e.client}</b>
                        <span>{e.title}</span>
                        <em>{e.value}</em>
                      </div>
                    </div>
                  ))}
                  {monthEvents.length === 0 && (
                    <div className="nb-side-empty">No events scheduled this month.</div>
                  )}
                </div>
                <div className="nb-side-hint">Click any day with an event to see details.</div>
              </React.Fragment>
            )}
          </aside>
        </div>
      </div>
    </section>
  );
}

function FinanceSection(){
  const live = window.useLiveData ? window.useLiveData() : null;
  const fmt  = window.fmtMoney  || (n => "₪" + n);
  const fmtS = window.fmtSigned || (n => (n>=0?"+":"") + "₪" + n);
  const [syncing, setSyncing] = React.useState(false);
  const [syncError, setSyncError] = React.useState(null);
  const onSync = async () => {
    if (syncing || !window.refreshBookings) return;
    setSyncing(true); setSyncError(null);
    try { await window.refreshBookings(); }
    catch (e) { setSyncError(e.message || "Sync failed"); }
    finally { setSyncing(false); }
  };

  // Loading state — keep the section's height so the page doesn't jump.
  if (!live) {
    return (
      <section id="finance" className="section">
        <div className="section-head">
          <div className="title">
            <span className="eyebrow">Live · Pulled from Monday</span>
            <h2>Finance <em>at a glance</em></h2>
          </div>
          <div className="meta"><span>Loading bookings…</span></div>
        </div>
      </section>
    );
  }

  const fyPct = Math.min(100, Math.round((live.fy.booked / live.fy.plan) * 100));
  const ytdPct = live.ytd.plan > 0 ? Math.round((live.ytd.booked / live.ytd.plan) * 100) : 0;
  const opColor = { MD: "var(--accent)", Events: "var(--gold)", WIX: "var(--teal)", MedOps: "var(--plum)" };
  const asOf = new Date(live.asOf);
  const asOfLabel = asOf.toLocaleString(undefined, { hour: "2-digit", minute: "2-digit", month: "short", day: "numeric" });

  return (
    <section id="finance" className="section">
      <div className="section-head">
        <div className="title">
          <span className="eyebrow">Live · Monday board {live.boardId} · {asOfLabel}</span>
          <h2>Toward <em>₪{(live.fy.plan/1_000_000).toFixed(2)}M</em> FY26</h2>
        </div>
        <div className="meta">
          <span><b>{fmt(live.fy.booked)}</b> booked</span>
          <span><b>{fmtS(live.ytd.variance)}</b> YTD variance</span>
          <span><b>{live.fy.daysLeft}</b> days left</span>
          <button onClick={onSync} disabled={syncing}
                  title={syncError || "Re-fetch from Monday Bookings board"}
                  style={{
                    padding:"4px 12px", borderRadius:999,
                    border:"1px solid " + (syncError ? "var(--red)" : "var(--line)"),
                    background:"var(--bg-card)", color:"var(--ink)",
                    fontSize:11, cursor: syncing ? "wait" : "pointer",
                    fontFamily:"'JetBrains Mono',monospace", letterSpacing:".06em",
                    textTransform:"uppercase", opacity: syncing ? .6 : 1,
                  }}>
            {syncing ? "Syncing…" : syncError ? "Retry sync" : "↻ Sync"}
          </button>
        </div>
      </div>
      <div className="finance-grid">
        <div className="fin-big">
          <div className="lbl">FY26 Booked Revenue</div>
          <div className="val">{fmt(live.fy.booked)}</div>
          <div className="trend">
            <span className={live.fy.onTrack ? "up" : "down"}>
              {live.fy.onTrack ? "● On track · YTD ahead" : "● Behind plan"}
            </span>
            {" "}of {fmt(live.fy.plan)} · gap {fmt(live.fy.gap)}
          </div>
          <div className="bar" style={{marginTop:14, height:8, background:"var(--line-soft)", borderRadius:999, overflow:"hidden"}}>
            <div style={{width:fyPct+"%", height:"100%", background:"var(--accent)"}}/>
          </div>
          <div className="trend" style={{marginTop:6, fontSize:12}}>{fyPct}% of plan</div>
        </div>
        <div className="fin-stack">
          <div className="fin-card">
            <div className="lbl">YTD Booked · {live.monthsClosedLabels[0]}–{live.monthsClosedLabels[live.monthsClosedLabels.length-1]}</div>
            <div className="val">{fmt(live.ytd.booked)}</div>
            <div className="sub">vs plan {fmt(live.ytd.plan)} · {ytdPct}%</div>
            <div className="bar"><div style={{width:Math.min(120,ytdPct)+"%", background:"var(--accent)"}}/></div>
          </div>
          <div className="fin-card">
            <div className="lbl">YTD Variance</div>
            <div className="val" style={{color: live.ytd.variance >= 0 ? "var(--green)" : "var(--red)"}}>
              {fmtS(live.ytd.variance)}
            </div>
            <div className="sub">{live.ytd.variance >= 0 ? "Ahead of plan" : "Behind plan"} (closed months only)</div>
          </div>
          <div className="fin-card">
            <div className="lbl">Awaiting Invoice</div>
            <div className="val">{fmt(live.status["Awaiting Invoice"] || 0)}</div>
            <div className="sub">to bill · Late! {fmt(live.status["Late!"] || 0)}</div>
          </div>
        </div>
        <div className="fin-breakdown">
          <div className="lbl">By Operation · YTD vs Plan ({live.monthsClosedLabels[0]}–{live.monthsClosedLabels[live.monthsClosedLabels.length-1]})</div>
          {live.byOperation.map(op => (
            <div key={op.op} className="seg-row">
              <span className="seg-name">{op.op}</span>
              <div className="seg-bar"><div style={{width:Math.min(100,op.pct)+"%", background:opColor[op.op] || "var(--accent)"}}/></div>
              <b>{fmt(op.booked)} <span style={{color:"var(--ink-muted)",fontWeight:400}}>· {op.pct}%</span></b>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function InternalSection(){
  // Subscribe to store
  const storeState = window.useStore(s => s);
  const team = window.Store ? window.Store.getCollection("team", TEAM) : TEAM;
  const hiring = window.Store ? window.Store.getCollection("hiring", HIRING) : HIRING;
  const internalTasks = window.Store ? window.Store.getCollection("internalTasks", INTERNAL_TASKS) : INTERNAL_TASKS;

  const update = (col, idx, patch) => window.Store && window.Store.updateInCollection(col, idx, patch);
  const remove = (col, idx) => window.Store && window.Store.removeFromCollection(col, idx);
  const add = (col, item) => window.Store && window.Store.addToCollection(col, item);

  const teamStatusOptions = [
    { value:"on-call", label:"on-call" },
    { value:"in-clinic", label:"in-clinic" },
    { value:"available", label:"available" },
    { value:"remote", label:"remote" },
    { value:"on-site: monday.com", label:"on-site: monday.com" },
  ];
  const hiringStatusOptions = [
    { value:"doing", label:"in pipeline" },
    { value:"ok", label:"offer sent" },
    { value:"blocked", label:"on hold" },
  ];
  const taskStatusOptions = [
    { value:"doing", label:"doing" },
    { value:"ok", label:"ok" },
    { value:"soon", label:"soon" },
    { value:"overdue", label:"overdue" },
    { value:"blocked", label:"blocked" },
  ];

  const avStatus = (s) => {
    if(s==="on-call") return "doing";
    if(s==="in-clinic") return "doing";
    if(s==="available") return "ok";
    if(s==="remote") return "ok";
    return "doing";
  };
  const initials = (n) => (n||"?").split(" ").map(w=>w[0]).slice(0,2).join("").toUpperCase();

  return (
    <section id="internal" className="section">
      <div className="section-head">
        <div className="title">
          <span className="eyebrow">Our house · What's running behind the curtain</span>
          <h2>Internal <em>things</em></h2>
        </div>
        <div className="meta">
          <span><b>{team.length}</b> Team</span>
          <span><b>{hiring.length}</b> Open roles</span>
          <span><b>₪1.04M</b> MRR</span>
        </div>
      </div>

      <div className="internal-grid three">
        {/* TEAM */}
        <div className="int-panel">
          <div className="p-head">
            <h3>Team <em>& HR</em></h3>
            <span className="meta">{team.length} members</span>
          </div>
          <div className="int-list">
            {team.map((m, i)=>(
              <div key={m._id || i} className="int-item">
                <div className="int-avatar" style={{ background: m.avatar || "linear-gradient(135deg,#E07856,#7C3F58)" }}>{m.initial || initials(m.name)}</div>
                <div className="int-info">
                  <b>
                    <EditableText
                      value={m.name}
                      onSave={(v)=>update("team", i, { name: v, initial: initials(v) })}
                      placeholder="Name"
                    />
                  </b>
                  <span>
                    <EditableText
                      value={m.role}
                      onSave={(v)=>update("team", i, { role: v })}
                      placeholder="Role"
                    />
                  </span>
                </div>
                <span className={"int-badge " + avStatus(m.status)}>
                  <EditableSelect
                    value={m.status}
                    options={teamStatusOptions}
                    onSave={(v)=>update("team", i, { status: v })}
                  />
                </span>
                <div className="inline-row-actions">
                  <button title="Remove" onClick={()=>remove("team", i)}><Icon.Trash/></button>
                </div>
              </div>
            ))}
            <button className="inline-add-row" onClick={()=>add("team", { name:"New member", role:"Role", status:"available", avatar:"linear-gradient(135deg,#7BA098,#4A6E68)", initial:"NM" })}>
              <Icon.Plus/> Add team member
            </button>
          </div>
        </div>

        {/* HIRING */}
        <div className="int-panel">
          <div className="p-head">
            <h3>Hiring <em>pipeline</em></h3>
            <span className="meta">{hiring.length} open</span>
          </div>
          <div className="int-list">
            {hiring.map((h, i)=>(
              <div key={h._id || i} className="int-item">
                <div className="int-avatar" style={{ background:"linear-gradient(135deg,#2A1D1A,#6B5C54)" }}>
                  <Icon.Users/>
                </div>
                <div className="int-info">
                  <b>
                    <EditableText
                      value={h.title}
                      onSave={(v)=>update("hiring", i, { title: v })}
                      placeholder="Role title"
                    />
                  </b>
                  <span>
                    <EditableText
                      value={h.loc}
                      onSave={(v)=>update("hiring", i, { loc: v })}
                      placeholder="Location · type"
                    />
                    {" · "}
                    <EditableText
                      value={h.stage}
                      onSave={(v)=>update("hiring", i, { stage: v })}
                      placeholder="Stage"
                    />
                  </span>
                </div>
                <span className={"int-badge " + (h.status || "doing")}>
                  <EditableSelect
                    value={h.status || "doing"}
                    options={hiringStatusOptions}
                    onSave={(v)=>update("hiring", i, { status: v })}
                  />
                </span>
                <div className="inline-row-actions">
                  <button title="Remove" onClick={()=>remove("hiring", i)}><Icon.Trash/></button>
                </div>
              </div>
            ))}
            <button className="inline-add-row" onClick={()=>add("hiring", { title:"New role", loc:"Tel Aviv · Full-time", stage:"screening", status:"doing" })}>
              <Icon.Plus/> Add open role
            </button>
          </div>
        </div>

        {/* INTERNAL TASKS */}
        <div className="int-panel">
          <div className="p-head">
            <h3>Internal <em>tasks</em></h3>
            <span className="meta">{internalTasks.length} open</span>
          </div>
          <div className="int-list">
            {internalTasks.map((t, i)=>(
              <div key={t._id || i} className="int-item">
                <div className="int-avatar" style={{ background:"linear-gradient(135deg,#E07856,#7C3F58)", fontSize:11 }}>
                  {initials(t.owner)}
                </div>
                <div className="int-info">
                  <b>
                    <EditableText
                      value={t.title}
                      onSave={(v)=>update("internalTasks", i, { title: v })}
                      placeholder="Task title"
                    />
                  </b>
                  <span>
                    <EditableText
                      value={t.owner}
                      onSave={(v)=>update("internalTasks", i, { owner: v })}
                      placeholder="Owner"
                    />
                    {" · Due "}
                    <EditableText
                      value={t.due}
                      onSave={(v)=>update("internalTasks", i, { due: v })}
                      placeholder="Date"
                    />
                  </span>
                </div>
                <span className={"int-badge " + (t.status || "doing")}>
                  <EditableSelect
                    value={t.status || "doing"}
                    options={taskStatusOptions}
                    onSave={(v)=>update("internalTasks", i, { status: v })}
                  />
                </span>
                <div className="inline-row-actions">
                  <button title="Remove" onClick={()=>remove("internalTasks", i)}><Icon.Trash/></button>
                </div>
              </div>
            ))}
            <button className="inline-add-row" onClick={()=>add("internalTasks", { title:"New task", owner:"Dr. Yohai", due:"This week", status:"doing" })}>
              <Icon.Plus/> Add internal task
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function AddCompanyModal({ open, segment, onClose, onAdd }){
  if(!open) return null;
  return <AddCompanyModalInner segment={segment} onClose={onClose} onAdd={onAdd}/>;
}

const ADD_LOGO_PRESETS = [
  "linear-gradient(135deg,#FF3D57,#FF8A3D)",
  "linear-gradient(135deg,#2563EB,#0EA5E9)",
  "linear-gradient(135deg,#1E293B,#475569)",
  "linear-gradient(135deg,#7C3F58,#D9A78E)",
  "linear-gradient(135deg,#E07856,#F3B89E)",
  "linear-gradient(135deg,#6B9B7A,#BFD8C4)",
  "linear-gradient(135deg,#0F172A,#334155)",
  "linear-gradient(135deg,#8B5CF6,#EC4899)",
  "linear-gradient(135deg,#2A1D1A,#6B5C54)",
  "linear-gradient(135deg,#0EA5A4,#22C55E)",
  "linear-gradient(135deg,#F59E0B,#EA580C)",
  "linear-gradient(135deg,#475569,#0F172A)",
];
const ADD_HEALTH_OPTIONS = [
  { k:"green", label:"Healthy" },
  { k:"amber", label:"Watch" },
  { k:"red",   label:"At risk" },
];
const ADD_REL_OPTIONS = ["new", "warm", "strong", "distant"];

function AddCompanyModalInner({ segment, onClose, onAdd }){
  const segLabel = segment === "md" ? "MD Service" : "Management";
  const [form, setForm] = React.useState({
    name: "",
    health: "green",
    mrr: "",
    renewalDate: "",
    renewalDays: 365,
    currentProject: "",
    nextCall: "Schedule kickoff",
    services: "",
    opportunity: "",
    champName: "",
    champRole: "",
    champEmail: "",
    champPhone: "",
    champRel:  "new",
    champNote: "",
    logoMode: "letter",
    logoLetter: "",
    logoBg: ADD_LOGO_PRESETS[0],
  });
  const set = (k,v) => setForm(f => ({...f, [k]:v}));

  // Auto-fill the monogram letter from the company name as the user types,
  // but only if the user hasn't manually customized it yet.
  const [letterTouched, setLetterTouched] = React.useState(false);
  React.useEffect(()=>{
    if(!letterTouched){
      const auto = (form.name || "·").trim()[0]?.toUpperCase() || "·";
      if(auto !== form.logoLetter) set("logoLetter", auto);
    }
  }, [form.name]);

  React.useEffect(()=>{
    const onKey = (e) => { if(e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return ()=>window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const valid = form.name.trim().length > 0;

  const submit = () => {
    if(!valid) return;
    const services = form.services.split(",").map(s=>s.trim()).filter(Boolean);
    const champ = (form.champName || form.champRole || form.champEmail) ? {
      name: form.champName || "TBD",
      role: form.champRole || "Primary Contact",
      email: form.champEmail || "",
      phone: form.champPhone || "",
      relationship: form.champRel,
      note: form.champNote || "",
      since: new Date().toLocaleDateString("en-US",{month:"short",year:"numeric"}),
    } : null;

    onAdd({
      segment,
      name: form.name.trim(),
      seed: {
        health: form.health,
        mrr: form.mrr || "TBD",
        services,
        renewalDays: parseInt(form.renewalDays) || 365,
        renewalDate: form.renewalDate || "A year from now",
        currentProject: form.currentProject || "Onboarding — program design in progress.",
        nextCall: form.nextCall || "Schedule kickoff",
        opportunity: form.opportunity || "To be assessed after kickoff.",
        openTasks: 1,
        champion: champ,
        poc: champ ? { name: champ.name, role: champ.role, email: champ.email } : { name:"TBD", role:"Primary Contact", email:"" },
        contacts: champ ? [{ name: champ.name, role: champ.role, initial: champ.name.split(" ").map(w=>w[0]).slice(0,2).join("") }] : [],
        tasks: [{ title:"Send kickoff agenda", due:"This week", status:"soon", done:false }],
        timeline: [{ type:"call", who:"Dr. Yohai", date:"Just now", title:"Client added", note:"Added to control center." }],
      },
      logo: {
        _logoMode: form.logoMode,
        _logoLetter: form.logoLetter,
        _logoBg: form.logoBg,
      },
    });
    onClose();
  };

  return (
    <React.Fragment>
      <div className="modal-scrim on" onClick={onClose}/>
      <div className="modal edit-modal on">
        <div className="edit-modal-head">
          <div className="edit-modal-preview" style={{ background: form.logoBg }}>
            {form.logoMode === "letter" ? (
              <span style={{
                fontFamily:"'Fraunces',serif", fontWeight:500,
                fontSize:30, color:"#fff", letterSpacing:"-.03em"
              }}>{(form.logoLetter || "·").toUpperCase().slice(0,2)}</span>
            ) : (
              <CompanyGlyph name={form.name || "New"} size={32}
                            override={{ _logoMode: form.logoMode, _logoBg: form.logoBg }}/>
            )}
          </div>
          <div className="edit-modal-titles">
            <span className="eyebrow">Add {segLabel} client</span>
            <h3>{form.name.trim() || "New client"}</h3>
          </div>
          <button className="bar-modal-close" onClick={onClose}><Icon.Close/></button>
        </div>

        <div className="edit-modal-body">
          <section className="edit-group">
            <h5>Identity</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Company name *</label>
                <input autoFocus value={form.name}
                       placeholder="e.g. Melio"
                       onChange={e=>set("name", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Health at onboarding</label>
                <div className="bf-status-pick">
                  {ADD_HEALTH_OPTIONS.map(h => (
                    <button key={h.k}
                            className={"bf-status-chip " + (form.health===h.k?"on":"")}
                            onClick={()=>set("health", h.k)}>
                      <span className={"health-dot " + h.k} style={{margin:0}}/>
                      {h.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </section>

          <section className="edit-group">
            <h5>Logo</h5>
            <div className="bf-field">
              <label>Mark style</label>
              <div className="bf-status-pick">
                <button className={"bf-status-chip " + (form.logoMode==="letter"?"on":"")} onClick={()=>set("logoMode","letter")}>
                  Letter monogram
                </button>
                <button className={"bf-status-chip " + (form.logoMode==="glyph"?"on":"")} onClick={()=>set("logoMode","glyph")}>
                  Abstract glyph
                </button>
              </div>
            </div>
            {form.logoMode === "letter" && (
              <div className="bf-field">
                <label>Letter (1–2 chars)</label>
                <input value={form.logoLetter} maxLength={2}
                       onChange={e=>{ setLetterTouched(true); set("logoLetter", e.target.value); }}/>
              </div>
            )}
            <div className="bf-field">
              <label>Color</label>
              <div className="logo-swatches">
                {ADD_LOGO_PRESETS.map((bg, i) => (
                  <button key={i}
                          className={"logo-swatch " + (form.logoBg === bg ? "on":"")}
                          style={{ background: bg }}
                          onClick={()=>set("logoBg", bg)}/>
                ))}
              </div>
            </div>
          </section>

          <section className="edit-group">
            <h5>Commercial</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>MRR</label>
                <input value={form.mrr} placeholder="₪48K" onChange={e=>set("mrr", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Renewal date</label>
                <input value={form.renewalDate} placeholder="e.g. Jul 12, 2026" onChange={e=>set("renewalDate", e.target.value)}/>
              </div>
            </div>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Days until renewal</label>
                <input type="number" value={form.renewalDays} onChange={e=>set("renewalDays", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Next call</label>
                <input value={form.nextCall} onChange={e=>set("nextCall", e.target.value)}/>
              </div>
            </div>
            <div className="bf-field">
              <label>Services (comma-separated)</label>
              <input value={form.services} placeholder="e.g. Health screening, On-site clinic" onChange={e=>set("services", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Current project / focus</label>
              <textarea rows={2} value={form.currentProject}
                        placeholder="What's the first deliverable for this client?"
                        onChange={e=>set("currentProject", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Expansion opportunity</label>
              <textarea rows={2} value={form.opportunity}
                        placeholder="Where do you see this account growing?"
                        onChange={e=>set("opportunity", e.target.value)}/>
            </div>
          </section>

          <section className="edit-group">
            <h5>Champion / Primary contact</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Name</label>
                <input value={form.champName} placeholder="e.g. Matan Bar" onChange={e=>set("champName", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Role</label>
                <input value={form.champRole} placeholder="e.g. CEO & Co-Founder" onChange={e=>set("champRole", e.target.value)}/>
              </div>
            </div>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Email</label>
                <input value={form.champEmail} onChange={e=>set("champEmail", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Phone</label>
                <input value={form.champPhone} onChange={e=>set("champPhone", e.target.value)}/>
              </div>
            </div>
            <div className="bf-field">
              <label>Relationship</label>
              <div className="bf-status-pick">
                {ADD_REL_OPTIONS.map(r => (
                  <button key={r}
                          className={"bf-status-chip " + (form.champRel===r?"on":"")}
                          onClick={()=>set("champRel", r)}>
                    {r}
                  </button>
                ))}
              </div>
            </div>
            <div className="bf-field">
              <label>Notes about this person</label>
              <textarea rows={3} value={form.champNote}
                        placeholder="Quirks, preferences, family, anything to remember"
                        onChange={e=>set("champNote", e.target.value)}/>
            </div>
          </section>
        </div>

        <div className="bar-modal-foot">
          <div className="bar-modal-foot-right">
            <button className="btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn-primary" onClick={submit} disabled={!valid}>
              Add client
            </button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, {
  MDServicesSection, ManagementSection, NewBusinessSection, InternalSection, AddCompanyModal, FinanceSection,
});
