// ============ TEMPLATES TAB ============
// Pre-built agents other users have hired. One-click "Hire" opens the
// architect modal pre-seeded with the template's brief.

// Each template carries the WHEN / DO / IF YOU CAN'T flow blocks the
// architect uses, so clicking Hire pre-fills the rule directly. Block ids
// must match those in shared/modals.jsx (ARCH_TRIGGERS / ARCH_ACTIONS /
// ARCH_FALLBACKS).
const TEMPLATES = [
  { id: "wa-ans",    name: "WhatsApp answerer",       role: "Customer support · WhatsApp", desc: "Answers customer questions on WhatsApp, books appointments, escalates anything weird.", tools: ["WhatsApp", "Sheets", "Phone"],     hires: "1,204 hires", color: "#E85D1A", flow: { when: "wa-msg",   do: ["answer", "tag"],     fallback: "ping-phone" } },
  { id: "fin-an",    name: "Monday morning analyst",  role: "Finance · weekly",            desc: "Reads your books every Monday and sends a plain-English summary with anything worth knowing.", tools: ["QuickBooks", "Stripe", "Email"], hires: "612 hires",   color: "#2DAF6B", flow: { when: "monday",   do: ["summary"],          fallback: "ping-email" } },
  { id: "lead-fol",  name: "Polite follow-upper",     role: "Sales · email + calls",       desc: "Follows up with every lead three times, days apart, stops the moment they reply.", tools: ["Gmail", "Calendar", "Phone"],          hires: "893 hires",   color: "#3B7CFF", flow: { when: "lead-new", do: ["reply", "tag"],     fallback: "ping-email" } },
  { id: "doc-rev",   name: "Contract reader",         role: "Legal · ad-hoc",              desc: "Reads any contract you forward and tells you in plain English where the weird stuff is.", tools: ["Gmail", "Drive"],                        hires: "287 hires",   color: "#B4488C", flow: { when: "forward",  do: ["draft", "summary"], fallback: "ping-email" } },
  { id: "inv-chase", name: "Invoice chaser",          role: "Finance · weekly",            desc: "Chases overdue invoices on a polite cadence. Stops if a customer is in active conversation.", tools: ["QuickBooks", "Email"],         hires: "418 hires",   color: "#D17C2A", flow: { when: "monday",   do: ["reply", "tag"],     fallback: "ping-email" } },
  { id: "calendar",  name: "Calendar host",           role: "Ops · email",                 desc: "Schedules meetings without the back-and-forth. Knows your buffers and protected time.", tools: ["Gmail", "Calendar"],                  hires: "765 hires",   color: "#7A5BCF", flow: { when: "email-in", do: ["book", "reply"],    fallback: "ping-email" } },
  { id: "review-rep",name: "Review reply-er",         role: "Customer · weekly",           desc: "Replies to every Google + Yelp review in your voice. Flags negative ones for your eyes.", tools: ["Google Biz", "Yelp"],                hires: "352 hires",   color: "#C95A4F", flow: { when: "review",   do: ["reply"],            fallback: "ping-email" } },
  { id: "intern",    name: "Research intern",         role: "Ops · ad-hoc",                desc: "Researches anything you ask — companies, people, markets — and gives you a one-pager.", tools: ["Web", "Drive"],                        hires: "1,089 hires", color: "#5B8DBF", flow: { when: "forward",  do: ["summary"],          fallback: "ping-email" } },
  { id: "stand-up",  name: "Stand-up summarizer",     role: "Ops · daily",                 desc: "Reads Slack standups, makes one short summary so you don't have to scroll.", tools: ["Slack", "Email"],                                  hires: "204 hires",   color: "#3DA28A", flow: { when: "monday",   do: ["summary"],          fallback: "ping-slack" } },
];

// Map a template's name (e.g. "WhatsApp answerer") to a short uppercase
// agent name like "WHATS" so the architect's name input shows something
// reasonable instead of the full template title.
function tplToPreset(t) {
  return {
    flow: t.flow,
    name: t.name.split(/\s+/)[0].replace(/[^a-zA-Z0-9]/g, "").slice(0, 8).toUpperCase(),
  };
}

function TemplatesTab({ onHire }) {
  const [cat, setCat] = useState("all");
  const [preview, setPreview] = useState(null);
  const cats = [
    ["all", "All"], ["sales", "Sales"], ["support", "Support"],
    ["finance", "Finance"], ["legal", "Legal"], ["ops", "Ops"],
  ];
  const filt = cat === "all" ? TEMPLATES : TEMPLATES.filter(t => t.role.toLowerCase().includes(cat));

  return (
    <div className="tp-page">
      <div className="tp-head">
        <div>
          <h2 className="tp-h">Hire someone in one click.</h2>
          <p className="tp-s">Templates other founders are running. Hire one as-is, or use it as a starting point.</p>
        </div>
        <div className="tp-cats">
          {cats.map(([k, l]) => (
            <button key={k} className={`tp-cat ${cat === k ? "is-on" : ""}`} onClick={() => setCat(k)}>{l}</button>
          ))}
        </div>
      </div>
      <div className="tp-grid">
        {filt.map(t => (
          <div key={t.id} className="tp-card">
            <div className="tp-card-top" style={{ background: t.color }}>
              <div className="tp-card-glyph">{t.name[0]}</div>
              <div className="tp-card-hires">{t.hires}</div>
            </div>
            <div className="tp-card-body">
              <h3 className="tp-card-n">{t.name}</h3>
              <div className="tp-card-r">{t.role}</div>
              <p className="tp-card-d">{t.desc}</p>
              <div className="tp-card-tools">
                {t.tools.map(tool => <span key={tool} className="tp-card-tool">{tool}</span>)}
              </div>
              <div className="tp-card-cta">
                <button className="btn btn-primary btn-sm" onClick={() => onHire(tplToPreset(t))}>Hire</button>
                <button className="btn btn-ghost btn-sm" onClick={() => setPreview(t)}>Preview</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {preview ? (
        <div className="tp-preview-overlay" onClick={() => setPreview(null)}>
          <div className="tp-preview" onClick={(e) => e.stopPropagation()}>
            <div className="tp-preview-top" style={{ background: preview.color }}>
              <div className="tp-card-glyph">{preview.name[0]}</div>
              <button className="tp-preview-x" onClick={() => setPreview(null)} aria-label="Close">×</button>
            </div>
            <div className="tp-preview-body">
              <h3 className="tp-preview-n">{preview.name}</h3>
              <div className="tp-card-r">{preview.role} · {preview.hires}</div>
              <p className="tp-preview-d">{preview.desc}</p>
              <div className="tp-preview-section">
                <div className="tp-preview-h">What it'll do day one</div>
                <ul className="tp-preview-list">
                  <li>Read your existing setup before doing anything.</li>
                  <li>Run on the schedule you set in Tools → Schedules.</li>
                  <li>Loop you in on anything outside its instructions.</li>
                </ul>
              </div>
              <div className="tp-preview-section">
                <div className="tp-preview-h">Tools it uses</div>
                <div className="tp-card-tools">
                  {preview.tools.map((t) => <span key={t} className="tp-card-tool">{t}</span>)}
                </div>
              </div>
              <div className="tp-preview-cta">
                <button className="btn btn-primary btn-sm" onClick={() => { onHire(tplToPreset(preview)); setPreview(null); }}>Hire as-is</button>
                <button className="btn btn-ghost btn-sm" onClick={() => setPreview(null)}>Close</button>
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

window.TemplatesTab = TemplatesTab;
