/* Calibrated Ascension HQ — client-side portal (what the client sees). */
const { useState: useStateC } = React;

const CP_STAGES = ["Mapped", "In build", "Review", "Waiting on you", "Delivered"];
const stageClass = (s) => ({ "Mapped": "mapped", "In build": "build", "Review": "review", "Waiting on you": "wait", "Delivered": "done" }[s] || "mapped");

/* Per-client offer/automation/website pipeline. Falls back to a generic shell. */
function getPipeline(id) {
  const P = {
    nova: {
      offers: [
        { name: "Free skin-quiz → ebook", tier: "Lead magnet", stage: "In build", who: "Iris" },
        { name: "$47 Starter Ritual kit", tier: "Low-ticket", stage: "Mapped", who: "Odin" },
        { name: "$197 Glow Method program", tier: "High-ticket", stage: "Mapped", who: "Odin" },
      ],
      automation: [
        { name: "Ebook delivery", stage: "In build", who: "Alma", formula: ["Capture form", "Delivery email", "Tag as lead", "Send the ebook"] },
        { name: "Starter-kit purchase", stage: "Mapped", who: "Alma", formula: ["Checkout", "Receipt + access", "Tag as buyer", "Post-purchase nurture"] },
      ],
      website: [
        { name: "Spring promo landing page", stage: "Review", who: "Alma" },
        { name: "Quiz funnel pages", stage: "In build", who: "Iris" },
      ],
      waiting: [
        { name: "Brand assets — logo + 3 product photos", since: "2 days", note: "This is holding the landing page" },
        { name: "Approve the ebook cover", since: "1 day", note: "" },
      ],
      approvals: [
        { id: "ca1", name: "Ebook recap + cover preview", desc: "Preview your lead-magnet ebook before we publish it." },
        { id: "ca2", name: "Starter-kit pricing — $47 + order bump", desc: "Approve and we'll build the checkout in your system." },
      ],
    },
    apex: {
      offers: [
        { name: "Free executive-coaching guide", tier: "Lead magnet", stage: "Delivered", who: "Iris" },
        { name: "$500 Strategy Intensive", tier: "Mid-ticket", stage: "In build", who: "Odin" },
        { name: "$6k Apex Mastermind", tier: "High-ticket", stage: "Review", who: "Odin" },
      ],
      automation: [
        { name: "Application funnel", stage: "Delivered", who: "Alma", formula: ["Application form", "Qualify + tag", "Book a call", "Reminder sequence"] },
        { name: "Guide delivery", stage: "In build", who: "Alma", formula: ["Capture form", "Delivery email", "Tag as lead", "Nurture sequence"] },
      ],
      website: [
        { name: "Mastermind sales page", stage: "Review", who: "Alma" },
      ],
      waiting: [
        { name: "Approve the mastermind sales-page copy", since: "today", note: "Final review before we publish" },
      ],
      approvals: [
        { id: "ca1", name: "Mastermind sales page", desc: "Preview the full page — approve or request changes." },
      ],
    },
  };
  return P[id] || {
    offers: [{ name: "Your core offer", tier: "Mapped from your intake", stage: "Mapped", who: "Odin" }],
    automation: [{ name: "Lead capture & delivery", stage: "Mapped", who: "Alma", formula: ["Capture form", "Delivery email", "Tag the lead", "Send the asset"] }],
    website: [{ name: "Landing page", stage: "Mapped", who: "Alma" }],
    waiting: [{ name: "Complete your onboarding intake", since: "—", note: "So we can map your offers" }],
    approvals: [],
  };
}

function Person({ name }) {
  return (<span className="cp-person"><span className="cp-person-i">{name[0]}</span>{name}</span>);
}

function PillarBlock({ icon, title, blurb, items, kind }) {
  return (
    <div className="cp-pillar">
      <div className="cp-pillar-h">
        <span className="cp-pillar-ico">{icon}</span>
        <div><div className="cp-pillar-t">{title}</div><div className="cp-pillar-b">{blurb}</div></div>
      </div>
      <div className="cp-items">
        {items.map((it, i) => (
          <div key={i} className="cp-item">
            <div className="cp-item-top">
              <div className="cp-item-name">{it.name}{it.tier && <span className="cp-tier">{it.tier}</span>}</div>
              <span className={`cp-stage ${stageClass(it.stage)}`}>{it.stage}</span>
            </div>
            {it.formula && (
              <div className="cp-formula">
                {it.formula.map((f, j) => (
                  <React.Fragment key={j}>
                    <span className="cp-step">{f}</span>
                    {j < it.formula.length - 1 && <span className="cp-arrow">→</span>}
                  </React.Fragment>
                ))}
              </div>
            )}
            <div className="cp-item-foot"><Person name={it.who} /></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ClientPortal({ client, onExit, flashToast }) {
  const p = getPipeline(client.id);
  const [done, setDone] = useStateC([]);
  const [comment, setComment] = useStateC("");
  const [thread, setThread] = useStateC([]);
  const allItems = [...p.offers, ...p.automation, ...p.website];
  const stageCount = (s) => allItems.filter((i) => i.stage === s).length;

  function decide(id, ok) {
    setDone((d) => [...d, id]);
    if (flashToast) flashToast(ok ? "Approved — thank you! The team is on it." : "Sent back with your notes.");
  }
  function postComment() {
    if (!comment.trim()) return;
    setThread((t) => [...t, { who: "You", text: comment.trim() }]);
    setComment("");
    if (flashToast) flashToast("Comment sent to your team");
  }

  return (
    <div className="cp-root">
      <div className="cp-bar">
        <div className="cp-brand">
          <span className="cp-logo" style={{ background: client.color }}>{client.initials}</span>
          <div><div className="cp-brand-n">{client.name}</div><div className="cp-brand-s">Project portal</div></div>
        </div>
        <div className="cp-bar-r">
          <span className="cp-preview-tag">Client preview</span>
          <button className="btn btn-ghost btn-sm" onClick={onExit}>{I.x} Exit client view</button>
        </div>
      </div>

      <div className="cp-scroll">
        <div className="cp-inner">
          <div className="cp-hero">
            <div className="cp-kicker">Your Ascension pipeline</div>
            <h1 className="cp-title">Here's where your build stands.</h1>
            <p className="cp-sub">Everything we're creating for you, who's on it, and where it is on the way to launch. Anything marked <b>Waiting on you</b> is where we need something to keep moving.</p>
          </div>

          <div className="cp-progress">
            {CP_STAGES.map((s) => (
              <div key={s} className={`cp-prog ${stageClass(s)}`} data-on={stageCount(s) > 0 ? "1" : null}>
                <div className="cp-prog-n">{stageCount(s)}</div>
                <div className="cp-prog-l">{s}</div>
              </div>
            ))}
          </div>

          {p.waiting && p.waiting.length > 0 && (
            <div className="cp-waiting">
              <div className="cp-waiting-h">{I.warn} Waiting on you — {p.waiting.length}</div>
              {p.waiting.map((w, i) => (
                <div key={i} className="cp-wait-row">
                  <div><div className="cp-wait-n">{w.name}</div>{w.note && <div className="cp-wait-note">{w.note}</div>}</div>
                  <span className="cp-since">{w.since}</span>
                </div>
              ))}
            </div>
          )}

          {p.approvals && p.approvals.length > 0 && (
            <div className="cp-section">
              <h2 className="cp-h2">Ready for your approval</h2>
              {p.approvals.map((a) => (
                <div key={a.id} className="cp-approval">
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="cp-appr-n">{a.name}</div>
                    <div className="cp-appr-d">{a.desc}</div>
                  </div>
                  {done.includes(a.id)
                    ? <span className="cp-appr-done">{I.check} Done</span>
                    : <div className="cp-appr-acts">
                        <button className="btn btn-ghost btn-sm">{I.doc} Preview</button>
                        <button className="btn btn-ghost btn-sm" onClick={() => decide(a.id, false)}>Request changes</button>
                        <button className="btn btn-primary btn-sm" onClick={() => decide(a.id, true)}>{I.check} Approve</button>
                      </div>}
                </div>
              ))}
            </div>
          )}

          <h2 className="cp-h2">In the works</h2>
          <PillarBlock icon={I.offers} title="Offers" blurb="Your value ladder — low, mid & high ticket" items={p.offers} />
          <PillarBlock icon={I.auto} title="Automation" blurb="The system built behind each offer" items={p.automation} />
          <PillarBlock icon={I.flow} title="Website & design" blurb="Pages and funnels we're building" items={p.website} />
          <div className="cp-handoff">{I.traffic} Social &amp; traffic is available as a handoff when you're ready — not part of this build.</div>

          <h2 className="cp-h2">Questions &amp; comments</h2>
          <div className="cp-comments">
            {thread.map((m, i) => (<div key={i} className="cp-comment"><span className="cp-person-i">{m.who[0]}</span><div>{m.text}</div></div>))}
            <div className="cp-comment-box">
              <textarea rows="2" value={comment} placeholder="Ask your team a question or leave a note…" onChange={(e) => setComment(e.target.value)} />
              <button className="btn btn-primary btn-sm" disabled={!comment.trim()} onClick={postComment}>{I.send} Send</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClientPortal });
