// E28E AI-Native view — assistant-first layout with thread, rails, composer
// 3-column: left rail (Today + Activity) | center (thread + chips + composer) | right rail (Pulse/Hours + Crew)

const AI_SUGGESTIONS = {
  owner: [
    "What needs my attention today?",
    "Approve the mulch reorder",
    "Draft a thank-you to Diane",
    "How are we tracking against May goal?",
  ],
  employee: [
    "What's on my schedule today?",
    "Get directions to Cedar Hill",
    "Who's on my crew today?",
    "Log my hours",
  ],
};

// Day 1 first-run setup prompts.
const AI_SETUP_SUGGESTIONS = {
  owner: [
    "Here's what my business does…",
    "Connect my email & Business socials",
    "Add my team",
    "What can you do for me?",
  ],
  employee: [
    "What is E28E?",
    "Show me how to clock in",
    "Connect my schedule",
  ],
};

const AI_FOLLOWUP_RESPONSES = {
  owner: {
    "what needs my attention today?": {
      reply: "Three things stand out — none urgent, all decidable in under a minute.",
      card: {
        title: "Priority queue",
        rows: [
          ["Diane Kapoor — deposit pending", "$8,400"],
          ["Cedar mulch low — auto-reorder ready", "Approve"],
          ["Mt. Tabor at 92% — schedule walk-through", "Today"],
        ],
      },
      followups: ["Approve mulch reorder", "Open Diane's file", "Message the crew"],
    },
    "approve the mulch reorder": {
      reply: "Reorder approved. 6 cu yd from Salem Stone, pickup tagged to Tuesday's run. Anya's notified.",
      followups: ["Show me other low inventory", "What else needs approval?"],
    },
    "draft a thank-you to diane": {
      reply: "Draft ready — warm, brief, references the phase 2 timeline. Want me to send, or revise?",
      card: {
        title: "Draft · D. Kapoor",
        rows: [
          ["Subject", "Welcoming you to phase 2"],
          ["Length", "82 words"],
          ["Tone", "Warm, professional"],
        ],
      },
      followups: ["Send as-is", "Make it shorter", "Read it to me"],
    },
    "how are we tracking against may goal?": {
      reply: "You're at $84.2k of the $110k May goal — 76% with 25 days remaining. Pace is +12% vs. last May, mostly driven by install revenue.",
      followups: ["Forecast end of month", "Compare to April", "What's driving growth?"],
    },
  },
  employee: {
    "what's on my schedule today?": {
      reply: "Three stops and one call. You're starting at Cedar Hill with Elena and Reggie.",
      card: {
        title: "Wed, May 6",
        rows: [
          ["8:30 — Crew dispatch · Cedar Hill", "On site"],
          ["10:00 — Design review w/ D. Kapoor", "Call"],
          ["12:30 — Salem Stone pickup", "Errand"],
          ["15:00 — Sellwood site walk", "On site"],
        ],
      },
      followups: ["Get directions to Cedar Hill", "Who's on my crew?", "Reschedule the 15:00"],
    },
    "get directions to cedar hill": {
      reply: "Sent to your phone. 14 min from the shop, taking 26th to avoid the Hawthorne backup.",
      followups: ["Notify the crew", "What's the gate code?"],
    },
    "who's on my crew today?": {
      reply: "Elena Marsh (design lead) and Reggie Sosa (install) — both clocked in at 7:48. Theo and Priya are off.",
      followups: ["Message the crew", "Show their hours this week"],
    },
    "log my hours": {
      reply: "Logged 4.0 hours to Cedar Hill (install) so far today. Want me to pre-fill the afternoon as Sellwood?",
      followups: ["Yes, pre-fill", "Split between projects"],
    },
  },
};

const aiFallback = (role) => ({
  reply:
    role === "owner"
      ? "I'd pull that together from your finances, projects, and inbox. Want me to draft a summary?"
      : "Let me check your tasks and schedule for that. Want me to ping Elena?",
  followups: AI_SUGGESTIONS[role].slice(0, 3),
});

const ReassureLine = () => (
  <div className="ai-reassure">
    <Ic.Undo size={12} />
    <span>You're always in control — E28E never sends anything without your yes. Review and undo anything.</span>
  </div>
);

const OwnerBriefing = ({ d, brand, onNavigate }) => {
  const r = d.recap;
  return (
    <div className="ai-hero">
      <div className="ai-hero-eyebrow">MORNING BRIEFING · WED, MAY 6</div>
      <h1 className="ai-hero-greet">Good morning, <span className="accent">Sam.</span></h1>
      <div className="ai-recap-banner">
        <div className="ai-recap-eyebrow"><Ic.Sparkle size={12} /> While you slept · this week</div>
        <div className="ai-recap-big">E28E handled <span className="accent">{r.actionCount} things</span> for you.</div>
        <div className="ai-recap-line">{r.line}</div>
        <div className="ai-recap-pills">
          {r.items.map((it, i) => (
            <button key={i} className="ai-recap-pill" data-tone={it.tone} onClick={() => onNavigate && onNavigate(it.target)}>
              <span className="ai-recap-pill-did">{it.did}</span>
              <span className="ai-recap-pill-val">{it.amount} <span className="ai-recap-pill-cat">{it.cat}</span></span>
              <Ic.Chevron size={12} className="ai-recap-pill-chev" />
            </button>
          ))}
        </div>
        <div className="ai-recap-foot">Pipeline &amp; drafts are potential — not money in the bank yet. Tap any row to open it.</div>
      </div>
      <p className="ai-hero-lede">
        A calm night otherwise. Three things are waiting for your yes — nothing urgent.
      </p>
      <ul className="ai-hero-updates">
        <li>
          <span className="ai-bullet" />
          <div>
            <div className="ai-update-title">Diane Kapoor approved the Tualatin proposal.</div>
            <div className="ai-update-sub">Deposit of $8,400 pending — I'll confirm receipt when it lands.</div>
          </div>
        </li>
        <li>
          <span className="ai-bullet" />
          <div>
            <div className="ai-update-title">A mulch reorder and two notes are drafted for your okay.</div>
            <div className="ai-update-sub">Approve or dismiss each in one tap — I won't send anything on my own.</div>
          </div>
        </li>
        <li>
          <span className="ai-bullet" />
          <div>
            <div className="ai-update-title">Revenue is pacing +12% vs. last Wednesday.</div>
            <div className="ai-update-sub">$18,420 today, mostly driven by the Cedar Hill install milestone.</div>
          </div>
        </li>
      </ul>
      <ReassureLine />
    </div>
  );
};

// Day 1 first-run — assistant front and center asking about the business.
const OwnerOnboarding = ({ d, brand }) => (
  <div className="ai-hero ai-onboard">
    <div className="ai-hero-eyebrow">WELCOME TO E28E · DAY ONE</div>
    <h1 className="ai-hero-greet">Tell me about <span className="accent">your business.</span></h1>
    <p className="ai-hero-lede">
      I'm E28E. Tell me what you do, who's on your team, and where your customers reach you —
      I'll start handling the busywork and show you the results in dollars, not minutes.
    </p>
    <div className="ai-onboard-steps">
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">1</span>
        <div>
          <div className="ai-onboard-step-t">Describe what you do</div>
          <div className="ai-onboard-step-s">A sentence is plenty — "landscape design in Portland."</div>
        </div>
      </div>
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">2</span>
        <div>
          <div className="ai-onboard-step-t">Connect your inbox</div>
          <div className="ai-onboard-step-s">Start with email — instant. Instagram &amp; Facebook connect as <strong>Business accounts</strong> and need a quick one-time approval (a couple minutes, once) before messages flow in.</div>
        </div>
      </div>
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">3</span>
        <div>
          <div className="ai-onboard-step-t">Add your team</div>
          <div className="ai-onboard-step-s">Everyone gets their own scoped view — owner or crew.</div>
        </div>
      </div>
    </div>
    <ReassureLine />
  </div>
);

const EmpBriefing = ({ d }) => {
  const r = d.empRecap;
  return (
    <div className="ai-hero">
      <div className="ai-hero-eyebrow">TODAY'S RUN · WED, MAY 6</div>
      <h1 className="ai-hero-greet">Good morning, <span className="accent">Jamie.</span></h1>
      <div className="ai-recap-banner">
        <div className="ai-recap-eyebrow"><Ic.Sparkle size={12} /> WHILE YOU WERE OFF · THIS MORNING</div>
        <div className="ai-recap-big">E28E handled <span className="accent">{r.count} things</span> for you.</div>
        <div className="ai-recap-line">{r.line}</div>
        <div className="ai-recap-pills">
          {r.items.map((it, i) => (
            <div key={i} className="ai-recap-pill ai-recap-pill-emp">
              <span className="ai-recap-pill-did">{it.did}</span>
              <span className="ai-recap-pill-val">{it.detail}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="ai-emp-proposal">
        <div className="ai-emp-proposal-top">
          <span className="ai-emp-proposal-icon"><Ic.Bot size={14} /></span>
          <div>
            <div className="ai-emp-proposal-title">Schedule Optimizer suggests starting at Cedar Hill.</div>
            <div className="ai-emp-proposal-sub">Saves 38 min of driving across your three stops.</div>
          </div>
        </div>
        <div className="ai-emp-proposal-actions">
          <button className="ai-chip ai-chip-accept"><Ic.Check size={11} /> Accept</button>
          <button className="ai-chip ai-chip-sm">Adjust</button>
        </div>
        <div className="ai-emp-control"><Ic.Shield size={11} /> {d.empControlNote}</div>
      </div>
      <p className="ai-hero-lede">
        Three site stops and one call. Elena and Reggie are both clocked in — you're on track.
      </p>
      <ul className="ai-hero-updates">
        <li>
          <span className="ai-bullet" />
          <div>
            <div className="ai-update-title">Your 8:30 dispatch is confirmed.</div>
            <div className="ai-update-sub">Elena + Reggie are in. 4-hour install window, gate code is 4421.</div>
          </div>
        </li>
        <li>
          <span className="ai-bullet" />
          <div>
            <div className="ai-update-title">Mt. Tabor walk-through at 15:30.</div>
            <div className="ai-update-sub">Third Coast Co. confirmed — project's at 92%, final sign-off expected.</div>
          </div>
        </li>
      </ul>
    </div>
  );
};

// Day 1 employee first-run — get your workspace set up.
const EmpOnboarding = ({ d }) => (
  <div className="ai-hero ai-onboard">
    <div className="ai-hero-eyebrow">WELCOME TO E28E · DAY ONE</div>
    <h1 className="ai-hero-greet">Welcome, <span className="accent">Jamie.</span></h1>
    <p className="ai-hero-lede">
      Let's get your workspace set up. Tell me your role and who's on your crew — I'll start
      sorting your day and taking the busywork off your plate so you can focus on the work.
    </p>
    <div className="ai-onboard-steps">
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">1</span>
        <div>
          <div className="ai-onboard-step-t">Confirm your role</div>
          <div className="ai-onboard-step-s">Crew lead, designer, install — whatever you do on site.</div>
        </div>
      </div>
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">2</span>
        <div>
          <div className="ai-onboard-step-t">Connect your schedule</div>
          <div className="ai-onboard-step-s">Your stops and dispatches flow in automatically.</div>
        </div>
      </div>
      <div className="ai-onboard-step">
        <span className="ai-onboard-num">3</span>
        <div>
          <div className="ai-onboard-step-t">Meet your AI agent</div>
          <div className="ai-onboard-step-s">Schedule Optimizer plans your routes and drafts your timesheet.</div>
        </div>
      </div>
    </div>
    <div className="ai-emp-control"><Ic.Shield size={11} /> {d.empControlNote}</div>
  </div>
);

const TodayPanel = ({ d }) => (
  <div className="ai-panel">
    <div className="ai-panel-head">
      <span className="ai-panel-title">Today</span>
      <span className="ai-panel-meta">May 6</span>
    </div>
    <div className="ai-today">
      {d.today.map((t, i) => (
        <div key={i} className="ai-today-row">
          <div className="ai-today-time">{t.time}</div>
          <div>
            <div className="ai-today-title">{t.title}</div>
            <div className="ai-today-sub">{t.sub}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const ActivityTicker = ({ d }) => {
  const items = [
    { t: "just now", text: "Lead Triage drafted reply to @portland_garden_collective" },
    { t: "8m", text: "New Instagram inquiry — back yard consult, May" },
    { t: "24m", text: "Diane Kapoor — Tualatin quote approved" },
    { t: "1h", text: "Marcus Lin asked about spring maintenance" },
    { t: "2h", text: "Stripe payout · $4,820 → Mechanics Bank" },
    { t: "3h", text: "@thirdcoast_co requested a feature interview" },
  ];
  return (
    <div className="ai-panel">
      <div className="ai-panel-head">
        <span className="ai-panel-title">Activity</span>
        <span className="ai-panel-meta">live</span>
      </div>
      <div className="ai-ticker">
        {items.map((it, i) => (
          <div key={i} className="ai-ticker-row">
            <div className="ai-ticker-time">{it.t}</div>
            <div className="ai-ticker-text">{it.text}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const PulseMetrics = ({ d }) => (
  <div className="ai-panel">
    <div className="ai-panel-head">
      <span className="ai-panel-title">Pulse</span>
      <span className="ai-panel-meta">today</span>
    </div>
    <div className="ai-pulse">
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">Revenue</div>
        <div className="ai-pulse-value">$18,420 <span className="ai-pulse-delta up">+12.4%</span></div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">May goal</div>
        <div className="ai-pulse-value">76% <span className="ai-pulse-sub">of $110k</span></div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">AR open</div>
        <div className="ai-pulse-value">$18,420 <span className="ai-pulse-sub">1 overdue</span></div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">AI handled</div>
        <div className="ai-pulse-value">23 <span className="ai-pulse-sub">of 35 today</span></div>
      </div>
    </div>
  </div>
);

const HoursPay = ({ d }) => (
  <div className="ai-panel">
    <div className="ai-panel-head">
      <span className="ai-panel-title">Hours &amp; pay</span>
      <span className="ai-panel-meta">this period</span>
    </div>
    <div className="ai-pulse">
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">Logged this week</div>
        <div className="ai-pulse-value">28.5 <span className="ai-pulse-sub">hrs</span></div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">Hourly</div>
        <div className="ai-pulse-value">$32.00</div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">Period pay</div>
        <div className="ai-pulse-value">$1,824 <span className="ai-pulse-sub">gross</span></div>
      </div>
      <div className="ai-pulse-row">
        <div className="ai-pulse-label">Next paycheck</div>
        <div className="ai-pulse-value">May 15 <span className="ai-pulse-sub">Fri</span></div>
      </div>
    </div>
    <div className="ai-payroll-note">
      <Ic.Shield size={11} /> Powered by your payroll provider. E28E shows your hours &amp; pay — it doesn't move the money.
    </div>
  </div>
);

const CrewPanel = ({ d }) => (
  <div className="ai-panel">
    <div className="ai-panel-head">
      <span className="ai-panel-title">Crew</span>
      <span className="ai-panel-meta">{d.employees.filter(e => e.status === "on").length} on</span>
    </div>
    <div className="ai-crew">
      {d.employees.map((e, i) => (
        <div key={i} className="ai-crew-row">
          <div className="ai-crew-av">
            {e.initials}
            <span className="ai-crew-status" data-s={e.status} />
          </div>
          <div>
            <div className="ai-crew-name">{e.name}</div>
            <div className="ai-crew-role">{e.role}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// Day 1 — rails wait quietly for the business to be set up.
const AIWaitPanel = ({ title, note }) => (
  <div className="ai-panel">
    <div className="ai-panel-head">
      <span className="ai-panel-title">{title}</span>
      <span className="ai-panel-meta">waiting</span>
    </div>
    <div className="ai-wait">
      <span className="ai-wait-bar" style={{ width: "70%" }} />
      <span className="ai-wait-bar" style={{ width: "52%" }} />
      <span className="ai-wait-bar" style={{ width: "60%" }} />
      <div className="ai-wait-note">{note}</div>
    </div>
  </div>
);

const AINative = ({ d, role, brand, day, onNavigate }) => {
  const [messages, setMessages] = React.useState([]);
  const [text, setText] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const threadRef = React.useRef(null);
  const taRef = React.useRef(null);

  const hasMessages = messages.length > 0;
  const isDay1 = day === "day1";
  const chips = isDay1 ? AI_SETUP_SUGGESTIONS[role] : AI_SUGGESTIONS[role];

  const send = (raw) => {
    const q = (raw ?? text).trim();
    if (!q) return;
    setMessages((m) => [...m, { from: "user", text: q }]);
    setText("");
    setTyping(true);
    setTimeout(() => {
      const key = q.toLowerCase();
      const resp = AI_FOLLOWUP_RESPONSES[role][key] || aiFallback(role);
      setTyping(false);
      setMessages((m) => [...m, { from: "bot", ...resp }]);
    }, 700 + Math.random() * 400);
  };

  React.useEffect(() => {
    if (hasMessages && threadRef.current) {
      threadRef.current.scrollTop = threadRef.current.scrollHeight;
    }
  }, [messages, typing, hasMessages]);

  const Briefing = isDay1
    ? (role === "owner" ? OwnerOnboarding : EmpOnboarding)
    : (role === "owner" ? OwnerBriefing : EmpBriefing);

  const composer = (
    <div className="ai-composer-wrap">
      <div className="ai-composer">
        <textarea
          ref={taRef}
          placeholder={role === "owner"
            ? "Ask about finances, projects, customers…"
            : "Ask about your tasks, schedule, materials…"}
          value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }
          }}
          rows={1}
        />
        <button className="ai-composer-send" disabled={!text.trim()} onClick={() => send()}>
          <Ic.Send size={13} />
        </button>
      </div>
      <div className="ai-composer-foot">
        <span className="ai-scope">
          <span className="ai-scope-dot" /> Scope: {role === "owner" ? "Full business" : "Crew Lead — tasks & projects"}
        </span>
        <span className="ai-composer-hint">⏎ to send · ⇧⏎ for newline</span>
      </div>
    </div>
  );

  return (
    <div className="ai-shell" data-screen-label={role === "owner" ? "Owner Assistant" : "Employee Assistant"}>
      <aside className="ai-rail ai-rail-left">
        {isDay1 ? (
          <AIWaitPanel title="Today" note="Connect your calendar and your day fills in here." />
        ) : (
          <>
            <TodayPanel d={d} />
            <ActivityTicker d={d} />
          </>
        )}
      </aside>

      <section className="ai-center">
        <div
          className="ai-thread"
          ref={threadRef}
          data-empty={!hasMessages ? "true" : "false"}
        >
          <div className="ai-thread-inner">
            <Briefing d={d} brand={brand} onNavigate={onNavigate} />
            {!hasMessages && (
              <>
                <div className="ai-composer-inline">{composer}</div>
                <div className="ai-chips-inline">
                  {chips.map((s, i) => (
                    <button key={i} className="ai-chip" onClick={() => send(s)}>
                      <Ic.Sparkle size={11} /> {s}
                    </button>
                  ))}
                </div>
              </>
            )}
            {hasMessages && (
              <div className="ai-messages">
                {messages.map((m, i) => (
                  <div key={i} className={`ai-msg ai-msg-${m.from}`}>
                    {m.from === "bot" && <div className="ai-msg-tag">E28E</div>}
                    <div className="ai-msg-body">{m.text}</div>
                    {m.card && (
                      <div className="ai-msg-card">
                        <div className="ai-msg-card-head">{m.card.title}</div>
                        <div className="ai-msg-card-body">
                          {m.card.rows.map((r, j) => (
                            <div key={j} className="ai-msg-card-row">
                              <span className="l">{r[0]}</span>
                              <span>{r[1]}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                    {m.followups && (
                      <div className="ai-msg-followups">
                        {m.followups.map((f, j) => (
                          <button key={j} className="ai-chip ai-chip-sm" onClick={() => send(f)}>{f}</button>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
                {typing && (
                  <div className="ai-msg ai-msg-bot">
                    <div className="ai-msg-tag">E28E</div>
                    <div className="typing"><span /><span /><span /></div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {hasMessages && composer}
      </section>

      <aside className="ai-rail ai-rail-right">
        {isDay1 ? (
          <AIWaitPanel title={role === "owner" ? "Pulse" : "Hours & pay"} note={role === "owner" ? "Connect your payment account to see revenue and goals." : "Connect your schedule to see your hours."} />
        ) : (
          <>
            {role === "owner" ? <PulseMetrics d={d} /> : <HoursPay d={d} />}
            <CrewPanel d={d} />
          </>
        )}
      </aside>
    </div>
  );
};

window.AINative = AINative;
