/* Website & Blog manager (B1/B2/B3). Route-controlled tabs + add/edit flows.
   window.WebsiteScreen — props: { tab: "site"|"blog"|"forms", builderIdx } */
const { useState } = React;

function WPanel({ title, icon, action, children, pad = 16 }) {
  return (
    <section style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xs)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
        {icon && <Icon name={icon} size={17} color="var(--text-brand)" />}
        <h3 style={{ fontSize: "var(--text-md)", fontWeight: 700, color: "var(--text-strong)" }}>{title}</h3>
        <div style={{ marginLeft: "auto" }}>{action}</div>
      </div>
      <div style={{ padding: pad }}>{children}</div>
    </section>
  );
}

function StatusTag({ s }) {
  const map = { Published: "success", Draft: "neutral", Scheduled: "info" };
  return <Badge tone={map[s] || "neutral"} size="sm" dot>{s}</Badge>;
}

/* ---------- B1: Site content & branding ---------- */
function SitePane() {
  const s = window.PT_DATA.site;
  const [theme, setTheme] = useState(s.theme);
  const blogOn = s.blogEnabled !== false;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 300px", gap: 16, alignItems: "start" }} className="pt-detail-grid">
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <WPanel title="Pages" icon="file-text" pad={0}
          action={<Button variant="brand" size="sm" icon="plus" onClick={() => navigate("/website/site/page/new")}>New page</Button>}>
          {s.pages.map((p, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
              <Icon name="file" size={16} color="var(--text-subtle)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, color: "var(--text-strong)", fontSize: "var(--text-base)" }}>{p.title}</div>
                <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }} className="tnum">{p.path} · edited {p.updated}</div>
              </div>
              <StatusTag s={p.status} />
              <IconButton icon="pencil" label="Edit page" onClick={() => navigate("/website/site/page/" + i)} />
            </div>
          ))}
        </WPanel>

        <WPanel title="Social connections" icon="share-2">
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {s.social.map((soc, i) => <SocialRow key={i} soc={soc} />)}
          </div>
        </WPanel>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <WPanel title="Branding" icon="palette">
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Field label="Site name"><Input defaultValue={s.name} /></Field>
            <Field label="Domain"><Input icon="globe" defaultValue={s.domain} /></Field>
            <Field label="Logo">
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: 10, border: "1px dashed var(--border-strong)", borderRadius: "var(--radius-md)", background: "var(--surface-sunken)" }}>
                <span style={{ width: 36, height: 36, borderRadius: 8, background: s.primary, display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="house" size={18} color="#fff" /></span>
                <button style={{ background: "none", border: "none", color: "var(--text-brand)", fontWeight: 600, fontSize: "var(--text-sm)", cursor: "pointer" }}>Replace logo</button>
              </div>
            </Field>
            <Field label="Theme">
              <div style={{ display: "flex", gap: 8 }}>
                {["Coastal", "Slate"].map((t) => (
                  <button key={t} onClick={() => setTheme(t)} style={{ flex: 1, padding: "9px", borderRadius: "var(--radius-md)", border: `1.5px solid ${theme === t ? "var(--harbor-400)" : "var(--border-default)"}`, background: theme === t ? "var(--harbor-50)" : "var(--surface-card)", cursor: "pointer", fontWeight: 600, fontSize: "var(--text-sm)", color: theme === t ? "var(--text-brand)" : "var(--text-body)" }}>{t}</button>
                ))}
              </div>
            </Field>
            <Field label="Brand colors">
              <div style={{ display: "flex", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 26, height: 26, borderRadius: 6, background: s.primary, border: "1px solid var(--border-default)" }} /><span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{s.primary}</span></div>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 26, height: 26, borderRadius: 6, background: s.accent, border: "1px solid var(--border-default)" }} /><span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{s.accent}</span></div>
              </div>
            </Field>
            <Button variant="primary" size="sm" icon="check" fullWidth>Save branding</Button>
          </div>
        </WPanel>

        <WPanel title="Blog" icon="newspaper">
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <Toggle checked={blogOn} onChange={(v) => { s.blogEnabled = v; PTStore.bump(); pushToast({ tone: v ? "success" : "info", title: v ? "Blog enabled" : "Blog disabled", body: v ? "The Blog tab and public blog are live." : "The blog is hidden from the public site." }); }} label="Enable blog on this site" />
            <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>
              {blogOn ? "Visitors can browse posts at /blog. Manage them from the Blog tab." : "The blog section is hidden from the public site and navigation."}
            </div>
          </div>
        </WPanel>
      </div>
    </div>
  );
}

function SocialRow({ soc }) {
  const [on, setOn] = useState(soc.on);
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 0", borderBottom: "1px solid var(--border-subtle)" }}>
      <span style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", background: on ? "var(--harbor-50)" : "var(--surface-sunken)", color: on ? "var(--harbor-600)" : "var(--text-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={soc.net} size={18} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, color: "var(--text-strong)", fontSize: "var(--text-base)", textTransform: "capitalize" }}>{soc.net}</div>
        <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{on ? soc.handle : "Not connected"}</div>
      </div>
      <Toggle checked={on} onChange={setOn} size="sm" />
    </div>
  );
}

/* ---------- B2: Blog manager ---------- */
function BlogPane() {
  const d = window.PT_DATA;
  const [tab, setTab] = useState("All");
  const tabs = ["All", "Published", "Scheduled", "Draft"];
  const rows = tab === "All" ? d.blogPosts : d.blogPosts.filter((p) => p.status === tab);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {d.site.blogEnabled === false && (
        <Banner tone="warning" title="Blog is disabled" action={<Button variant="secondary" size="sm" onClick={() => navigate("/website/site")}>Enable</Button>}>
          Posts below are hidden from the public site. Enable the blog on the Site &amp; branding tab.
        </Banner>
      )}
      <WPanel title="Blog posts" icon="newspaper" pad={0}
        action={<Button variant="brand" size="sm" icon="plus" onClick={() => navigate("/website/blog/new")}>Write post</Button>}>
        <div style={{ display: "flex", gap: 6, padding: "12px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
          {tabs.map((t) => (
            <button key={t} onClick={() => setTab(t)} style={{ padding: "5px 12px", borderRadius: "var(--radius-pill)", border: "1px solid var(--border-default)", cursor: "pointer", fontWeight: 600, fontSize: "var(--text-xs)", background: tab === t ? "var(--harbor-500)" : "var(--surface-card)", color: tab === t ? "#fff" : "var(--text-muted)" }}>{t}</button>
          ))}
        </div>
        <div className="pt-scroll-x">
        <table style={{ width: "100%", minWidth: 720, borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ background: "var(--surface-sunken)" }}>
              {["Title", "Category", "Author", "Date", "Views", "Status", ""].map((h, i) => (
                <th key={i} style={{ textAlign: i >= 4 && i < 6 ? "right" : "left", padding: "9px 14px", fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", fontWeight: 700, color: "var(--text-muted)", borderBottom: "1px solid var(--border-default)", whiteSpace: "nowrap" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((p, i) => <BlogRow key={i} p={p} onEdit={() => navigate("/website/blog/" + d.blogPosts.indexOf(p))} />)}
          </tbody>
        </table>
        </div>
      </WPanel>
    </div>
  );
}

function BlogRow({ p, onEdit }) {
  const [hover, setHover] = useState(false);
  return (
    <tr onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onClick={onEdit} style={{ cursor: "pointer", borderBottom: "1px solid var(--border-subtle)", background: hover ? "var(--surface-hover)" : "transparent" }}>
      <td style={{ padding: "11px 14px", fontWeight: 600, color: "var(--text-strong)", fontSize: "var(--text-base)", maxWidth: 280 }}>{p.title}</td>
      <td style={{ padding: "11px 14px" }}><Badge tone="brand" size="sm">{p.cat}</Badge></td>
      <td style={{ padding: "11px 14px", fontSize: "var(--text-sm)", color: "var(--text-body)", whiteSpace: "nowrap" }}>{p.author}</td>
      <td style={{ padding: "11px 14px", fontSize: "var(--text-sm)", color: "var(--text-muted)", whiteSpace: "nowrap" }} className="tnum">{p.date}</td>
      <td style={{ padding: "11px 14px", fontSize: "var(--text-sm)", textAlign: "right", color: "var(--text-body)" }} className="tnum">{p.views ? p.views.toLocaleString() : "—"}</td>
      <td style={{ padding: "11px 14px", textAlign: "right" }}><StatusTag s={p.status} /></td>
      <td style={{ padding: "11px 8px", textAlign: "right" }}><IconButton icon="pencil" label="Edit" /></td>
    </tr>
  );
}

/* ---------- B3: Webform builder ---------- */
function WebformsPane() {
  const d = window.PT_DATA;
  return (
    <WPanel title="Webforms" icon="clipboard-list" pad={0}
      action={<Button variant="brand" size="sm" icon="plus" onClick={() => navigate("/website/forms/new")}>New webform</Button>}>
      {d.webforms.map((f, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
          <span style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--harbor-50)", color: "var(--harbor-600)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="clipboard-list" size={20} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: "var(--text-base)" }}>{f.name}</span>
              {f.createsProperty && <Badge tone="success" size="sm" icon="building-2">Creates property</Badge>}
            </div>
            <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>Embedded on: {f.embedded}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontWeight: 700, color: "var(--text-strong)", fontSize: "var(--text-base)" }} className="tnum">{f.submissions}</div>
            <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-subtle)" }}>submissions</div>
          </div>
          <Button variant="secondary" size="sm" icon="pencil" onClick={() => navigate("/website/forms/" + i)}>Edit</Button>
        </div>
      ))}
    </WPanel>
  );
}

function FormBuilder({ idx }) {
  const d = window.PT_DATA;
  const isNew = idx === "new";
  const wf = !isNew ? d.webforms[idx] : null;
  const [fields, setFields] = useState(d.formFields.map((f) => ({ ...f })));
  const [success, setSuccess] = useState("message");
  const [thankYou, setThankYou] = useState("Thanks — we got your details. Someone from our team will be in touch shortly with your cash offer.");
  const [redirect, setRedirect] = useState("");
  const [copied, setCopied] = useState(false);
  function toggle(i) { setFields((fs) => fs.map((f, j) => j === i ? { ...f, on: !f.on } : f)); }
  function req(i) { setFields((fs) => fs.map((f, j) => j === i ? { ...f, required: !f.required } : f)); }
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
        <Button variant="secondary" size="sm" icon="arrow-left" onClick={() => navigate("/website/forms")}>All webforms</Button>
        <h3 style={{ fontSize: "var(--text-lg)", fontWeight: 700, color: "var(--text-strong)" }}>{isNew ? "New webform" : wf.name + " — builder"}</h3>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <Button variant="secondary" size="sm" icon="eye">Preview</Button>
          <Button variant="primary" size="sm" icon="check" onClick={() => { pushToast({ tone: "success", title: "Webform saved", body: "Fields and on-submit settings published." }); navigate("/website/forms"); }}>Save &amp; publish</Button>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 380px", gap: 16, alignItems: "start" }} className="pt-detail-grid">
        {/* config */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <WPanel title="Fields" icon="list" pad={0}>
            {fields.map((f, i) => (
              <div key={f.key} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderBottom: "1px solid var(--border-subtle)", opacity: f.on ? 1 : 0.55 }}>
                <Icon name="grip-vertical" size={16} color="var(--text-subtle)" style={{ cursor: "grab" }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, color: "var(--text-strong)", fontSize: "var(--text-base)" }}>{f.label}</div>
                  <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{f.type}</div>
                </div>
                <button onClick={() => req(i)} disabled={!f.on} style={{ background: f.required ? "var(--ember-50)" : "var(--surface-sunken)", color: f.required ? "var(--ember-700)" : "var(--text-muted)", border: "1px solid " + (f.required ? "var(--ember-200)" : "var(--border-default)"), borderRadius: "var(--radius-pill)", padding: "3px 10px", fontSize: "var(--text-2xs)", fontWeight: 700, cursor: f.on ? "pointer" : "not-allowed" }}>{f.required ? "Required" : "Optional"}</button>
                <Toggle checked={f.on} onChange={() => toggle(i)} size="sm" />
              </div>
            ))}
            <div style={{ padding: 12 }}>
              <button style={{ width: "100%", padding: "9px", borderRadius: "var(--radius-md)", border: "1px dashed var(--border-strong)", background: "var(--surface-sunken)", color: "var(--text-brand)", fontWeight: 600, fontSize: "var(--text-sm)", cursor: "pointer", fontFamily: "var(--font-sans)", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}><Icon name="plus" size={15} /> Add custom field</button>
            </div>
          </WPanel>

          <WPanel title="On submit" icon="zap">
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <Radio name="succ" value="message" checked={success === "message"} onChange={setSuccess} label="Show a thank-you message" />
                <Radio name="succ" value="redirect" checked={success === "redirect"} onChange={setSuccess} label="Redirect to a URL" />
              </div>
              {success === "message"
                ? <Field label="Thank-you message" hint="Shown to the visitor after they submit.">
                    <Textarea rows={3} value={thankYou} onChange={(e) => setThankYou(e.target.value)} />
                  </Field>
                : <Field label="Redirect URL"><Input icon="link" placeholder="https://…/thank-you" value={redirect} onChange={(e) => setRedirect(e.target.value)} /></Field>}
              <div style={{ padding: 12, borderRadius: "var(--radius-md)", background: "var(--success-soft)", display: "flex", gap: 9, fontSize: "var(--text-sm)", color: "var(--success-text)" }}>
                <Icon name="circle-check" size={17} style={{ marginTop: 1 }} />
                <span>Creates a lead + property, <b>notifies the owner</b>, and attaches the submitter as a contact.</span>
              </div>
            </div>
          </WPanel>

          <WPanel title="Embed snippet" icon="code">
            <div style={{ fontFamily: "var(--font-mono)", fontSize: "var(--text-xs)", color: "var(--slate-100)", background: "var(--slate-900)", padding: 14, borderRadius: "var(--radius-md)", overflowX: "auto", whiteSpace: "pre" }}>{'<script src="https://beaconhomes.proptrackr.site/embed/sell-my-house.js"></script>'}</div>
            <div style={{ marginTop: 10 }}>
              <Button variant="secondary" size="sm" icon={copied ? "check" : "copy"} onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }}>{copied ? "Copied" : "Copy embed code"}</Button>
            </div>
          </WPanel>
        </div>

        {/* live preview */}
        <div style={{ position: "sticky", top: 22 }}>
          <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", color: "var(--text-subtle)", marginBottom: 8 }}>Live preview</div>
          <div style={{ borderRadius: "var(--radius-lg)", border: "1px solid var(--border-default)", overflow: "hidden", boxShadow: "var(--shadow-md)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 12px", background: "var(--slate-100)", borderBottom: "1px solid var(--border-default)" }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--slate-300)" }} /><span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--slate-300)" }} /><span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--slate-300)" }} />
            </div>
            <div data-pt-theme="coastal" style={{ padding: 18, background: "var(--site-bg)" }}>
              <div style={{ fontFamily: "var(--site-font-display)", fontSize: 19, fontWeight: 700, color: "var(--site-fg)", marginBottom: 12 }}>Get your cash offer</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {fields.filter((f) => f.on).map((f) => (
                  <div key={f.key}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "var(--site-fg)", marginBottom: 4 }}>{f.label}{f.required && <span style={{ color: "var(--site-accent)" }}> *</span>}</div>
                    {f.type === "Dropdown"
                      ? <div style={{ height: 36, borderRadius: "var(--site-radius)", border: "1px solid var(--site-border)", background: "var(--site-bg)", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 10px", fontSize: 13, color: "var(--site-muted)" }}>Select…<Icon name="chevron-down" size={14} /></div>
                      : f.type === "Long text"
                        ? <div style={{ height: 56, borderRadius: "var(--site-radius)", border: "1px solid var(--site-border)", background: "var(--site-bg)" }} />
                        : <div style={{ height: 36, borderRadius: "var(--site-radius)", border: "1px solid var(--site-border)", background: "var(--site-bg)" }} />}
                  </div>
                ))}
                <button style={{ marginTop: 4, background: "var(--site-accent)", color: "#fff", border: "none", borderRadius: "var(--site-radius)", padding: "11px", fontWeight: 700, fontSize: 14, cursor: "pointer" }}>Get my cash offer</button>
              </div>
            </div>
          </div>
          {success === "message" && (
            <div style={{ marginTop: 12, padding: 14, borderRadius: "var(--radius-lg)", border: "1px solid var(--success)", background: "var(--success-soft)" }}>
              <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "var(--tracking-caps)", color: "var(--success-text)", marginBottom: 6 }}>After submit, visitor sees</div>
              <div style={{ display: "flex", gap: 9 }}>
                <Icon name="circle-check" size={18} color="var(--success)" style={{ marginTop: 1, flex: "none" }} />
                <div style={{ fontSize: "var(--text-sm)", color: "var(--text-body)", lineHeight: "var(--leading-normal)" }}>{thankYou || "Thank you."}</div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function WebsiteScreen({ tab = "site", builderIdx = null }) {
  const blogOn = window.PT_DATA.site.blogEnabled !== false;
  const nav = [["site", "Site & branding", "layout-panel-top"], ["blog", "Blog", "newspaper"], ["forms", "Webforms", "clipboard-list"]];
  return (
    <div style={{ padding: 22, display: "grid", gridTemplateColumns: "220px minmax(0,1fr)", gap: 18, alignItems: "start" }} className="pt-detail-grid">
      <nav style={{ background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", padding: 8, boxShadow: "var(--shadow-xs)", display: "flex", flexDirection: "column", gap: 2 }}>
        {nav.map(([k, label, icon]) => {
          const disabled = k === "blog" && !blogOn;
          return (
            <button key={k} onClick={() => !disabled && navigate("/website/" + k)} disabled={disabled} title={disabled ? "Blog is disabled" : ""}
              style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: "var(--radius-md)", border: "none", cursor: disabled ? "not-allowed" : "pointer", textAlign: "left", background: tab === k ? "var(--surface-selected)" : "transparent", color: tab === k ? "var(--text-brand)" : "var(--text-body)", fontWeight: tab === k ? 600 : 500, fontSize: "var(--text-sm)", fontFamily: "var(--font-sans)", opacity: disabled ? 0.5 : 1 }}>
              <Icon name={icon} size={16} /> {label}{disabled && <Icon name="eye-off" size={13} style={{ marginLeft: "auto" }} />}
            </button>
          );
        })}
        <a href="../website/index.html" target="_blank" style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: "var(--radius-md)", textDecoration: "none", color: "var(--text-muted)", fontWeight: 500, fontSize: "var(--text-sm)", borderTop: "1px solid var(--border-subtle)" }}>
          <Icon name="external-link" size={16} /> View live site
        </a>
      </nav>
      <div>
        {tab === "site" && <SitePane />}
        {tab === "blog" && <BlogPane />}
        {tab === "forms" && (builderIdx != null ? <FormBuilder idx={builderIdx} /> : <WebformsPane />)}
      </div>
    </div>
  );
}
window.WebsiteScreen = WebsiteScreen;
