// Home / Landing page — DakLab Property AI
// Renault DS — white canvas, hairline cards, single primary accent.

const { useState, useMemo, useRef, useEffect } = React;

// ---------- Icons (Lucide-style, 1.6 stroke) ----------
const Icon = {
  list: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 7h16M4 12h16M4 17h10"/></svg>,
  snapshot: <svg width="18" height="18" 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>,
  contact: <svg width="18" height="18" 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>,
  trend: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>,
  refresh: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/><path d="M3 21v-5h5"/></svg>,
  send: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  attach: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M21 12.5l-8.5 8.5a5 5 0 0 1-7-7l8.5-8.5a3.5 3.5 0 0 1 5 5L10.5 19a2 2 0 0 1-2.8-2.8L15 9"/></svg>,
  plus: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>,
  check: <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5 9-11"/></svg>,
  search: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  views: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>,
  saves: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M19 21l-7-5-7 5V4a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1z"/></svg>,
};

// TEMP: demo link to Property Hub — remove when routing is wired
const TEMP_PH_DEMO_ADDR = "2318 North Sherman Williams Blvd";
const TEMP_PH_DEMO_HREF = "../property-hub/index.html";
const TEMP_OPP_DEMO_ADDR = "1840 North Ave";
const TEMP_OPP_DEMO_HREF = "../workflow/index.html";

// ---------- Health ring (compact, copied vibe from PropertyHub) ----------
function MiniRing({ value, size = 44 }) {
  const r = (size - 6) / 2;
  const c = 2 * Math.PI * r;
  const dash = (value / 100) * c;
  const tone = value >= 70 ? "#5e8a3a" : value >= 45 ? "#d68a2a" : "#b34141";
  return (
    <div style={{position:"relative", width: size, height: size, flexShrink:0}}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#f2f2f2" strokeWidth="3"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={tone} strokeWidth="3"
          strokeDasharray={`${dash} ${c}`} strokeLinecap="butt"
          transform={`rotate(-90 ${size/2} ${size/2})`}/>
      </svg>
      <div style={{position:"absolute", inset:0, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", lineHeight:1}}>
        <div style={{fontSize:13, fontWeight:700, color:"#000"}}>{value}</div>
        <div style={{fontSize:7.5, fontWeight:700, letterSpacing:0.3, textTransform:"uppercase", color:"#888", marginTop:1}}>Health</div>
      </div>
    </div>
  );
}

// ---------- Confetti ----------
function fireConfetti(originEl) {
  const canvas = document.createElement("canvas");
  canvas.className = "home-confetti";
  document.body.appendChild(canvas);
  const ctx = canvas.getContext("2d");
  const dpr = window.devicePixelRatio || 1;
  const resize = () => {
    canvas.width = window.innerWidth * dpr;
    canvas.height = window.innerHeight * dpr;
    canvas.style.width = window.innerWidth + "px";
    canvas.style.height = window.innerHeight + "px";
    ctx.scale(dpr, dpr);
  };
  resize();

  const rect = originEl ? originEl.getBoundingClientRect() : null;
  const ox = rect ? rect.left + rect.width / 2 : window.innerWidth / 2;
  const oy = rect ? rect.top + rect.height / 2 : window.innerHeight / 2;

  const rootStyles = getComputedStyle(document.documentElement);
  const primary = rootStyles.getPropertyValue("--r-primary").trim() || "#bd2136";
  const primaryDeep = rootStyles.getPropertyValue("--r-primary-deep").trim() || "#8f1929";
  const colors = [primary, "#000000", primaryDeep, "#ffffff", "#5e8a3a"];
  const N = 140;
  const particles = [];
  for (let i = 0; i < N; i++) {
    const angle = Math.random() * Math.PI * 2;
    const speed = 6 + Math.random() * 10;
    particles.push({
      x: ox, y: oy,
      vx: Math.cos(angle) * speed,
      vy: Math.sin(angle) * speed - 4,
      g: 0.32 + Math.random() * 0.18,
      rot: Math.random() * Math.PI,
      vr: (Math.random() - 0.5) * 0.4,
      w: 6 + Math.random() * 8,
      h: 3 + Math.random() * 5,
      color: colors[(Math.random() * colors.length) | 0],
      life: 0,
      maxLife: 90 + Math.random() * 40,
    });
  }

  let raf;
  function tick() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let alive = 0;
    for (const p of particles) {
      p.life++;
      if (p.life > p.maxLife) continue;
      alive++;
      p.vy += p.g;
      p.vx *= 0.99;
      p.x += p.vx;
      p.y += p.vy;
      p.rot += p.vr;
      const a = 1 - p.life / p.maxLife;
      ctx.save();
      ctx.globalAlpha = Math.max(0, a);
      ctx.translate(p.x, p.y);
      ctx.rotate(p.rot);
      ctx.fillStyle = p.color;
      ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
      ctx.restore();
    }
    if (alive > 0) raf = requestAnimationFrame(tick);
    else {
      cancelAnimationFrame(raf);
      canvas.remove();
    }
  }
  tick();
}

// ---------- Seed data ----------
const SEED_OPPS = [
  {
    id: "opp-1840",
    address: "1840 North Ave",
    source: "Owner Contact Finder",
    status: "Owner Contact Found",
    signal: "Strong equity signal · ready for strategy prep",
    recommendation: "Create a Listing Strategy Blueprint before outreach.",
    primary: "Create Blueprint",
  },
  {
    id: "opp-72grove",
    address: "72 Grove Street",
    source: "CRM Import",
    status: "Contact Linked",
    signal: "Imported lead · property snapshot still needed",
    recommendation: "Run a Property Snapshot to qualify the opportunity.",
    primary: "Run Snapshot",
  },
];

const SEED_ACTIVES = [
  {
    id: "active-2318",
    address: "2318 North Sherman Williams Blvd",
    locality: "Raleigh, NC 27609",
    photo: "https://photos.zillowstatic.com/fp/67a1fa617ed04801179748f8a942a9e4-cc_ft_1536.webp",
    health: 56,
    summary: "Solid exposure, but saves are lagging. Prepare the seller for a pricing conversation.",
    stats: { views: 707, saves: 48, dom: 2, rate: "6.8%", rateLabel: "save-to-view" },
    rec: "Send a seller report and prepare a strategic price adjustment conversation.",
    primary: "Create Seller Update",
    secondary: "Preview",
  },
  {
    id: "active-88harbor",
    address: "88 Harbor Point",
    locality: "Cary, NC 27519",
    photo: null,
    health: 61,
    summary: "Views are steady, but saves are lagging. Refresh the lead photo.",
    stats: { views: 412, saves: 11, dom: 18, rate: "2.7%", rateLabel: "save-to-view" },
    rec: "Refresh marketing before the listing starts to feel stale.",
    primary: "Refresh Marketing",
    secondary: "Preview",
  },
];

const SEED_LIBRARY = [
  { id: "lib-1", address: "193 Crossings Pl", state: "Active listing", source: "Realtor.com profile", activity: "Imported 2 days ago", status: "Ready" },
  { id: "lib-2", address: "1402 E Lenoir St", state: "Active listing", source: "Single address", activity: "Health checked today", status: "Needs review" },
  { id: "lib-3", address: "555 Main St", state: "Opportunity", source: "Owner Contact Finder", activity: "Strategy started", status: "Ready" },
  { id: "lib-4", address: "789 Pine Ridge", state: "Sold", source: "CRM import", activity: "Imported last week", status: "Archived" },
  { id: "lib-5", address: "1840 North Ave", state: "Opportunity", source: "Owner Contact Finder", activity: "Contact found today", status: "Ready" },
  { id: "lib-6", address: "72 Grove Street", state: "Imported", source: "CRM import", activity: "Contact linked today", status: "Ready" },
  { id: "lib-7", address: "2318 North Sherman Williams Blvd", state: "Active listing", source: "Zillow profile", activity: "Seller update ready", status: "Ready" },
  { id: "lib-8", address: "88 Harbor Point", state: "Active listing", source: "Zillow profile", activity: "Health checked today", status: "Watch" },
  { id: "lib-9", address: "412 Oakwood Dr", state: "Imported", source: "CRM import", activity: "Imported 4 days ago", status: "Ready" },
  { id: "lib-10", address: "67 Lakeshore Ct", state: "Opportunity", source: "Owner Contact Finder", activity: "Snapshot complete", status: "Ready" },
  { id: "lib-11", address: "1209 Brookline Way", state: "Active listing", source: "Realtor.com profile", activity: "Marketing refreshed", status: "Ready" },
  { id: "lib-12", address: "904 Forest Hills Dr", state: "Sold", source: "Single address", activity: "Closed last month", status: "Archived" },
];

// ---------- Hero section ----------
function HomeHero() {
  return (
    <section className="home-hero">
      <div className="home-hero-overline">DakLab Property AI</div>
      <h1 className="home-hero-title">Hey Brad, let's get started.</h1>
      <div className="home-prompt">
        <textarea
          className="home-prompt-input"
          placeholder="Search an address, paste a Zillow link, or ask DakLab what to do next."
          rows={2}
        />
        <div className="home-prompt-foot">
          <button className="home-prompt-attach">{Icon.attach}<span>Attach</span></button>
          <button className="home-prompt-send" aria-label="Send">{Icon.send}</button>
        </div>
      </div>
      <div className="home-quick">
        {[
          { label: "Listing Strategy", icon: Icon.list },
          { label: "Property Snapshot", icon: Icon.snapshot },
          { label: "Owner Contact", icon: Icon.contact },
          { label: "Seller Update", icon: Icon.trend },
          { label: "Marketing Refresh", icon: Icon.refresh },
        ].map((t) => (
          <button key={t.label} className="home-quick-tile">
            <span className="home-quick-tile-icon">{t.icon}</span>
            <span className="home-quick-tile-label">{t.label}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

// ---------- Seller Opportunity card ----------
function OpportunityCard({ opp, isConverting, onConvert }) {
  const btnRef = useRef(null);
  const hasOpportunityHub = opp.address === TEMP_OPP_DEMO_ADDR;
  return (
    <div className={`home-opp ${isConverting ? "is-converting" : ""}`}>
      <div className="home-opp-head">
        <div className="home-opp-tag">Opportunity</div>
        <span className="home-opp-status">{opp.status}</span>
      </div>
      <h3 className="home-opp-addr">
        {hasOpportunityHub ? (
          <a href={TEMP_OPP_DEMO_HREF} className="home-temp-ph-link">{opp.address}</a>
        ) : (
          opp.address
        )}
      </h3>
      <div className="home-opp-source">{opp.source}</div>
      <p className="home-opp-signal">{opp.signal}</p>
      <div className="home-opp-rec">
        <div className="home-opp-meta-lbl">Recommended next step</div>
        <p>{opp.recommendation}</p>
      </div>
      <div className="home-opp-actions">
        {hasOpportunityHub ? (
          <a className="home-opp-primary" href={TEMP_OPP_DEMO_HREF}>{opp.primary}</a>
        ) : (
          <button className="home-opp-primary">{opp.primary}</button>
        )}
        <button
          ref={btnRef}
          className="home-opp-secondary"
          onClick={() => onConvert(opp.id, btnRef.current)}
        >
          Convert to signed
        </button>
      </div>
    </div>
  );
}

// ---------- Active Listing card ----------
function ActiveCard({ listing }) {
  return (
    <div className="home-active">
      <div className="home-active-head">
        <div className="home-active-photo">
          {listing.photo
            ? <img src={listing.photo} alt={listing.address}/>
            : <div className="home-active-photo-ph">photo</div>}
        </div>
        <div className="home-active-meta">
          <div className="home-active-tag">Active Listing</div>
          <h3 className="home-active-addr">
            {listing.address === TEMP_PH_DEMO_ADDR ? (
              <a href={TEMP_PH_DEMO_HREF} className="home-temp-ph-link">{listing.address}</a>
            ) : (
              listing.address
            )}
          </h3>
          <div className="home-active-locality">{listing.locality}</div>
        </div>
        <MiniRing value={listing.health} />
      </div>
      <p className="home-active-summary">{listing.summary}</p>
      <div className="home-active-stats">
        <div className="home-active-stat">
          <div className="home-active-stat-num">{listing.stats.views}</div>
          <div className="home-active-stat-lbl">Views</div>
        </div>
        <div className="home-active-stat">
          <div className="home-active-stat-num">{listing.stats.saves}</div>
          <div className="home-active-stat-lbl">Saves</div>
        </div>
        <div className="home-active-stat">
          <div className="home-active-stat-num">{listing.stats.dom}</div>
          <div className="home-active-stat-lbl">DOM</div>
        </div>
        <div className="home-active-stat">
          <div className="home-active-stat-num-pct">{listing.stats.rate}</div>
          <div className="home-active-stat-lbl">{listing.stats.rateLabel}</div>
        </div>
      </div>
      <div className="home-active-rec">
        <div className="home-active-rec-lbl">Recommended next action</div>
        <p className="home-active-rec-text">{listing.rec}</p>
      </div>
      <div className="home-active-actions">
        <button className="r-btn r-btn-primary" style={{background:"#000", color:"#fff"}}>{listing.primary}</button>
        <button className="r-btn r-btn-outline-dark">{listing.secondary}</button>
      </div>
    </div>
  );
}

// ---------- Property Library ----------
function PropertyLibrary() {
  const [query, setQuery] = useState("");
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return SEED_LIBRARY;
    return SEED_LIBRARY.filter((r) => r.address.toLowerCase().includes(q));
  }, [query]);

  const statusClass = (s) => {
    const k = s.toLowerCase();
    if (k === "ready") return "home-table-status-ready";
    if (k === "needs review") return "home-table-status-review";
    if (k === "archived") return "home-table-status-archived";
    if (k === "watch") return "home-table-status-watch";
    return "";
  };

  return (
    <section className="home-card">
      <div className="home-library-head">
        <div className="home-card-head-title">Property Library</div>
        <div className="home-library-tools">
          <input
            type="text"
            className="home-library-search"
            placeholder="Search by address"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <button className="home-library-add" aria-label="Add property">{Icon.plus}</button>
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="home-library-empty">
          <h3 className="home-library-empty-title">No properties found</h3>
          <p className="home-library-empty-body">Add this address to start a new Property Workspace.</p>
          <button className="home-library-empty-cta">Add Property</button>
        </div>
      ) : (
        <div className="home-library-scroll">
          <table className="home-table">
            <thead>
              <tr>
                <th>Property</th>
                <th>Property State</th>
                <th>Source</th>
                <th>Last Activity</th>
                <th>Status</th>
                <th style={{textAlign:"right"}}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.id}>
                  <td className="home-table-addr">
                    {row.address === TEMP_PH_DEMO_ADDR ? (
                      <a href={TEMP_PH_DEMO_HREF} className="home-temp-ph-link">{row.address}</a>
                    ) : row.address === TEMP_OPP_DEMO_ADDR ? (
                      <a href={TEMP_OPP_DEMO_HREF} className="home-temp-ph-link">{row.address}</a>
                    ) : (
                      row.address
                    )}
                  </td>
                  <td className="home-table-state">{row.state}</td>
                  <td className="home-table-source">{row.source}</td>
                  <td className="home-table-activity">{row.activity}</td>
                  <td>
                    <span className={`home-table-status ${statusClass(row.status)}`}>{row.status}</span>
                  </td>
                  <td style={{textAlign:"right"}}>
                    <div className="home-table-actions" style={{justifyContent:"flex-end"}}>
                      <button className="home-table-btn">Details</button>
                      <button className="home-table-btn-ghost">More</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}

// ---------- App shell ----------
function HomeApp() {
  const [opps, setOpps] = useState(SEED_OPPS);
  const [actives, setActives] = useState(SEED_ACTIVES);
  const [convertingId, setConvertingId] = useState(null);

  function handleConvert(oppId, originEl) {
    if (convertingId) return;
    const opp = opps.find((o) => o.id === oppId);
    if (!opp) return;

    setConvertingId(oppId);
    fireConfetti(originEl);

    setTimeout(() => {
      const newActive = {
        id: `active-${oppId}`,
        address: opp.address,
        locality: "—",
        photo: null,
        health: 50 + Math.floor(Math.random() * 20),
        summary: "Just converted from an opportunity. Confirm details and prep launch marketing.",
        stats: { views: 0, saves: 0, dom: 0, rate: "—", rateLabel: "save-to-view" },
        rec: "Set list price, photos, and launch the listing on your channels.",
        primary: "Launch Listing",
        secondary: "Edit Details",
      };
      setActives((prev) => [...prev, newActive]);
      setOpps((prev) => prev.filter((o) => o.id !== oppId));
      setConvertingId(null);
    }, 360);
  }

  return (
    <div className="ph-shell" style={{gridTemplateColumns:"88px 1fr"}}>
      <Sidebar active="home" />
      <main className="home-main">
        <HomeHero />

        <section>
          <div className="home-intro-overline">Your property workspace</div>
          <h2 className="home-intro-title">Turn any address into listing strategy, marketing, and seller-ready communication.</h2>
        </section>

        <section className="home-workspace">
          {/* Seller Opportunities */}
          <div className="home-card">
            <div className="home-card-head">
              <div className="home-card-head-title">Seller Opportunities</div>
              <button className="home-card-head-link">View all</button>
            </div>
            <div className="home-opps">
              {opps.length === 0 ? (
                <div className="home-opps-empty">No opportunities right now.</div>
              ) : (
                opps.map((o) => (
                  <OpportunityCard
                    key={o.id}
                    opp={o}
                    isConverting={convertingId === o.id}
                    onConvert={handleConvert}
                  />
                ))
              )}
            </div>
          </div>

          {/* Signed Listings */}
          <div className="home-card">
            <div className="home-card-head">
              <div className="home-card-head-title">Signed Listings</div>
              <button className="home-card-head-link">Refresh</button>
            </div>
            <div className="home-actives">
              {actives.length === 0 ? (
                <div className="home-actives-empty">No signed listings yet.</div>
              ) : (
                actives.map((a) => <ActiveCard key={a.id} listing={a} />)
              )}
            </div>
          </div>
        </section>

        <PropertyLibrary />
      </main>
    </div>
  );
}

window.HomeApp = HomeApp;
