// Sidebar — left rail navigation with stacked icon+label pattern
const { useState: useSidebarState, useEffect: useSidebarEffect, useRef: useSidebarRef } = React;

const FlyoutIcon = {
  add: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16"/><path d="M12 8v8M8 12h8"/></svg>,
  zillow: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16"/><text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="700" fill="currentColor" stroke="none" fontFamily="inherit">Z</text></svg>,
  realtor: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16"/><text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="700" fill="currentColor" stroke="none" fontFamily="inherit">R</text></svg>,
  list: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 7h16M4 12h16M4 17h10"/></svg>,
  snapshot: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="5" width="16" height="14"/><path d="M4 9h16"/></svg>,
  owner: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6"/></svg>,
  update: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 4v16M3 18l5-5 4 4 8-8"/></svg>,
  refresh: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 8h12M4 12h16M8 16h12"/><path d="M16 6l2 2-2 2M8 14l-2 2 2 2"/></svg>,
  message: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  photo: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="5" width="16" height="14"/><circle cx="9" cy="10" r="1.5"/><path d="M4 17l5-5 4 4 2-2 5 5"/></svg>,
  search: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  inbox: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 5h16v14H4z"/><path d="M4 8l8 6 8-6"/></svg>,
  doc: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M7 3h7l4 4v14H7z"/><path d="M14 3v5h5M9 13h6M9 17h6"/></svg>,
  blueprint: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16"/><path d="M8 8h8M8 12h5M8 16h8"/></svg>,
  chart: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 19V5M8 17v-5M13 17V8M18 17v-8M4 19h17"/></svg>,
  palette: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 4a8 8 0 0 0 0 16h2a2 2 0 0 0 1.4-3.4l-.4-.4a2 2 0 0 1 1.4-3.4H18a4 4 0 0 0 0-8z"/><circle cx="8.5" cy="10" r="1"/><circle cx="11.5" cy="8" r="1"/><circle cx="7.5" cy="14" r="1"/></svg>,
  home: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1z"/></svg>,
  qr: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 5h5v5H5zM14 5h5v5h-5zM5 14h5v5H5zM14 14h2v2h-2zM17 17h2v2h-2zM18 14h1M14 18v1"/></svg>,
  video: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="6" width="12" height="12"/><path d="M16 10l5-3v10l-5-3z"/></svg>,
  feedback: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 5h14v10H8l-3 4z"/><path d="M9 9h6M9 12h4"/></svg>,
};

function FlyoutFrame({ title, subtitle, label, className = "", onClose, onMouseEnter, onMouseLeave, children }) {
  const ref = useSidebarRef(null);
  useSidebarEffect(() => {
    function onDoc(e) {
      if (ref.current && !ref.current.contains(e.target)) onClose();
    }
    function onKey(e) { if (e.key === "Escape") onClose(); }
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

  return (
    <div
      className={`ph-flyout ${className}`}
      ref={ref}
      role="dialog"
      aria-label={label}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      <span className="ph-flyout-bridge" aria-hidden="true" />
      <header className="ph-flyout-head">
        <div>
          <h2 className="r-heading-md" style={{margin:0, lineHeight:1.1}}>{title}</h2>
          <p className="r-body-sm" style={{margin:"6px 0 0", color:"#666"}}>{subtitle}</p>
        </div>
        <button className="ph-icon-only" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
        </button>
      </header>
      {children}
    </div>
  );
}

function NewFlyout({ onClose, onMouseEnter, onMouseLeave }) {

  const startProperty = [
    { key: "address", label: "Address Search", icon: FlyoutIcon.add },
    { key: "zillow", label: "Zillow Link", icon: FlyoutIcon.zillow },
    { key: "realtor", label: "Realtor Import", icon: FlyoutIcon.realtor },
  ];

  const workflows = [
    { key: "strategy", label: "Listing Strategy", icon: FlyoutIcon.list },
    { key: "snapshot", label: "Property Snapshot", icon: FlyoutIcon.snapshot },
    { key: "owner", label: "Owner Contact", icon: FlyoutIcon.owner },
    { key: "update", label: "Seller Update", icon: FlyoutIcon.update },
    { key: "refresh", label: "Marketing Refresh", icon: FlyoutIcon.refresh },
    { key: "message", label: "Seller Message", icon: FlyoutIcon.message },
  ];

  const recent = ["1409 Westbrook Lane", "193 Crossings Pl"];

  return (
    <FlyoutFrame
      title="New Property Workflow"
      subtitle="Start with an address, listing link, import, or seller communication."
      label="New Property Workflow"
      onClose={onClose}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      <div className="ph-flyout-section">
        <div className="r-overline ph-flyout-overline">Start a Property</div>
        <div className="ph-flyout-grid">
          {startProperty.map(it => (
            <button key={it.key} className="ph-flyout-tile">
              <span className="ph-flyout-tile-icon">{it.icon}</span>
              <span className="ph-flyout-tile-label">{it.label}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="ph-flyout-section">
        <div className="r-overline ph-flyout-overline">Workflows</div>
        <div className="ph-flyout-grid">
          {workflows.map(it => (
            <button key={it.key} className="ph-flyout-tile">
              <span className="ph-flyout-tile-icon">{it.icon}</span>
              <span className="ph-flyout-tile-label">{it.label}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="ph-flyout-section">
        <div className="r-overline ph-flyout-overline">Recent</div>
        <div className="ph-flyout-recent">
          {recent.map(r => (
            <button key={r} className="ph-flyout-recent-item">
              <span>{r}</span>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M9 6l6 6-6 6"/></svg>
            </button>
          ))}
        </div>
      </div>
    </FlyoutFrame>
  );
}

function ToolsFlyout({ onClose, onMouseEnter, onMouseLeave }) {
  const groups = [
    {
      title: "Property Research",
      tools: [
        { key: "snapshot-report", label: "Property Snapshot Report", description: "Property value, equity, owner details, and market status.", icon: FlyoutIcon.snapshot },
        { key: "owner-contact", label: "Owner Contact Finder", description: "Verified phones, emails, mailing addresses, and ownership details.", icon: FlyoutIcon.owner },
        { key: "contact-enrichment", label: "Contact Enrichment", description: "Look up phone numbers to get owner names, addresses, and alternate phones.", icon: FlyoutIcon.search },
      ],
    },
    {
      title: "Strategy & Outreach",
      tools: [
        { key: "listing-strategy", label: "Listing Strategy Blueprints", description: "Generate and manage listing blueprints and market reports.", icon: FlyoutIcon.chart, href: "../workflow/index.html" },
        { key: "buyer-strategy", label: "Buyer Strategy Blueprints", description: "Create, edit, and share buyer strategy blueprints.", icon: FlyoutIcon.blueprint },
        { key: "ai-recommend", label: "See If AI Recommends You or Your Competition", description: "Check how buyers and sellers see you in AI answers.", icon: FlyoutIcon.search },
        { key: "seller-zestimate", label: "Seller Zestimate Outreach", description: "Generate personalized homeowner emails based on Zillow Zestimate.", icon: FlyoutIcon.home },
      ],
    },
    {
      title: "Marketing & Messaging",
      tools: [
        { key: "listing-description", label: "Listing Description Engine", description: "Create MLS-ready listing descriptions that highlight key features.", icon: FlyoutIcon.doc },
        { key: "website-copy", label: "Website Copy Engine", description: "Create high-performing web pages that engage and convert.", icon: FlyoutIcon.list },
        { key: "smart-message", label: "Smart Message Builder", description: "Craft texts and emails that feel personal and get replies.", icon: FlyoutIcon.message },
        { key: "inbox", label: "AI for Your Inbox", description: "Forward emails to get summaries, reply drafts, or direct assistance.", icon: FlyoutIcon.inbox },
        { key: "qr-code", label: "QR Code Builder", description: "Create customized QR codes with your brand colors and logo.", icon: FlyoutIcon.qr },
      ],
    },
    {
      title: "Creative Studio",
      tools: [
        { key: "photo-editor", label: "AI Photo Editor", description: "Retouch photos, apply filters, and make professional adjustments.", icon: FlyoutIcon.photo },
        { key: "virtual-staging", label: "Virtual Staging Pro", description: "Edit listing photos with AI-powered retouching and staging.", icon: FlyoutIcon.home },
        { key: "watercolor", label: "Watercolor Studio", description: "Turn listing photos into watercolor-style images.", icon: FlyoutIcon.palette },
        { key: "video-generator", label: "AI Video Generator", description: "Create videos from text prompts and images using DakLab AI.", icon: FlyoutIcon.video },
      ],
    },
    {
      title: "Documents & Platform",
      tools: [
        { key: "contract-analyzer", label: "Contract Analyzer", description: "Advanced contract analysis with document intelligence.", icon: FlyoutIcon.doc },
        { key: "inspection-analyzer", label: "Inspection Report Analyzer", description: "Summarize inspection reports, cost estimates, and negotiation strategies.", icon: FlyoutIcon.doc },
        { key: "feedback", label: "Give Feedback", description: "Help improve DakLab with your thoughts and suggestions.", icon: FlyoutIcon.feedback },
      ],
    },
  ];

  return (
    <FlyoutFrame
      title="Tools"
      subtitle="Browse DakLab tools by the job you need to get done."
      label="Tools"
      className="ph-tools-flyout"
      onClose={onClose}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      {groups.map(group => (
        <div key={group.title} className="ph-flyout-section">
          <div className="r-overline ph-flyout-overline">{group.title}</div>
          <div className="ph-flyout-grid ph-tools-flyout-grid">
            {group.tools.map(tool => (
              <button
                key={tool.key}
                type="button"
                className="ph-flyout-tile ph-tools-flyout-tile"
                onClick={() => { if (tool.href) window.location.href = tool.href; }}
              >
                <span className="ph-flyout-tile-icon">{tool.icon}</span>
                <span className="ph-flyout-tile-label">{tool.label}</span>
                <span className="ph-tools-flyout-desc">{tool.description}</span>
              </button>
            ))}
          </div>
        </div>
      ))}
    </FlyoutFrame>
  );
}

function Sidebar({ active = "home", onSelect }) {
  const [flyoutOpen, setFlyoutOpen] = useSidebarState(null);
  const closeTimer = useSidebarRef(null);

  const cancelClose = () => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
  };
  const scheduleClose = () => {
    cancelClose();
    closeTimer.current = setTimeout(() => setFlyoutOpen(null), 140);
  };
  const openNow = (flyout) => { cancelClose(); setFlyoutOpen(flyout); };

  useSidebarEffect(() => () => cancelClose(), []);

  useSidebarEffect(() => {
    document.body.classList.toggle("ph-flyout-active", Boolean(flyoutOpen));
    return () => document.body.classList.remove("ph-flyout-active");
  }, [flyoutOpen]);

  const items = [
    { key: "new", label: "New", flyout: "new", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 5v14M5 12h14"/></svg> },
    { key: "home", label: "Home", href: "../home/index.html", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1z"/></svg> },
    { key: "properties", label: "Properties", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="4" width="16" height="16"/><path d="M4 9h16M9 9v11"/></svg> },
    { key: "contacts", label: "Contacts", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.5 3-6 7-6s7 2.5 7 6"/></svg> },
    { key: "tools", label: "Tools", flyout: "tools", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 20l4-4M7 16l4-10 5 2-4 10z"/><path d="M14 8l4 4-4 8"/></svg> },
    { key: "workflow", label: "Workflow", href: "../workflow/index.html", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 3v6M12 15v6M9 12l3-3 3 3M9 12l3 3 3-3"/></svg> },
    { key: "more", label: "More", icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 7h14M5 12h14M5 17h14"/></svg> },
  ];

  return (
    <>
      <aside className="ph-sidebar ph-sidebar-stacked">
        <div className="ph-sidebar-logo">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
            <rect x="4" y="4" width="16" height="16"/>
            <path d="M12 8v8M8 12h8"/>
          </svg>
        </div>
        <nav className="ph-sidebar-nav">
          {items.map(it => {
            const isActive = !flyoutOpen && active === it.key;
            const flyoutHover = it.flyout
              ? { onMouseEnter: () => openNow(it.flyout), onMouseLeave: scheduleClose, onFocus: () => openNow(it.flyout), onBlur: scheduleClose }
              : {};
            const onClick = (e) => {
              if (it.flyout) { e.preventDefault(); setFlyoutOpen(it.flyout); }
              else if (it.href) { setFlyoutOpen(null); /* let anchor navigate */ }
              else { setFlyoutOpen(null); onSelect && onSelect(it.key); }
            };
            const cls = `ph-sidebar-item ${isActive ? "is-active" : ""} ${it.flyout && flyoutOpen === it.flyout ? "is-active" : ""}`;
            if (it.href) {
              return (
                <a key={it.key} className={cls} href={it.href} title={it.label} style={{textDecoration:"none"}}>
                  <span className="ph-sidebar-icon">{it.icon}</span>
                  <span className="ph-sidebar-label">{it.label}</span>
                </a>
              );
            }
            return (
              <button
                key={it.key}
                className={cls}
                onClick={onClick}
                title={it.label}
                {...flyoutHover}>
                <span className="ph-sidebar-icon">{it.icon}</span>
                <span className="ph-sidebar-label">{it.label}</span>
              </button>
            );
          })}
        </nav>
        <div className="ph-sidebar-foot">
          <button className="ph-sidebar-avatar" aria-label="Account">RC</button>
        </div>
      </aside>
      {flyoutOpen === "new" && (
        <NewFlyout
          onClose={() => setFlyoutOpen(null)}
          onMouseEnter={() => openNow("new")}
          onMouseLeave={scheduleClose}
        />
      )}
      {flyoutOpen === "tools" && (
        <ToolsFlyout
          onClose={() => setFlyoutOpen(null)}
          onMouseEnter={() => openNow("tools")}
          onMouseLeave={scheduleClose}
        />
      )}
    </>
  );
}
window.Sidebar = Sidebar;
