// Property Library table — shared by Home and Properties pages
const { useState, useMemo, useEffect } = React;

const LibraryIcon = {
  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>
  ),
  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>
  ),
  plus: (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
    >
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
};

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";
const TEMP_BUYER_HREF = TEMP_OPP_DEMO_HREF;
const TEMP_SELLER_HREF = TEMP_PH_DEMO_HREF;
const TEMP_DETAILS_HREF = "../property-details/index.html";
const PAGE_SIZE = 15;

const LIBRARY_PHOTOS = [
  "https://photos.zillowstatic.com/fp/4a376df669de9d892706f84791815580-p_c.jpg",
  "https://photos.zillowstatic.com/fp/379874af86a7c450c684addb277465cf-p_c.jpg",
  "https://photos.zillowstatic.com/fp/2c88534c959af34d366b4daf89a8114a-p_c.jpg",
  "https://photos.zillowstatic.com/fp/8bc619fe7b3e5b2a17ea3fb8ac39fae7-p_c.jpg",
  "https://photos.zillowstatic.com/fp/59bfd1964eac50a6ee48b81ed39858b2-cc_ft_768.webp",
  "https://photos.zillowstatic.com/fp/6efbce87fd36aff08e095fd8b19464be-cc_ft_768.webp",
  "https://photos.zillowstatic.com/fp/79b6eabbcff86ce1d61ee1d0b088d07f-cc_ft_768.webp",
  "https://photos.zillowstatic.com/fp/67a1fa617ed04801179748f8a942a9e4-cc_ft_1536.webp",
];

const SEED_LIBRARY = [
  {
    id: "lib-8",
    address: "88 Harbor Point",
    locality: "Cary, NC 27519",
    photo: LIBRARY_PHOTOS[0],
    source: "Zillow profile",
    activity: "Health checked today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-12",
    address: "904 Forest Hills Dr",
    locality: "Durham, NC 27705",
    photo: LIBRARY_PHOTOS[1],
    source: "Single address",
    activity: "Closed last month",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-5",
    address: "1840 North Ave",
    locality: "Raleigh, NC 27604",
    photo: LIBRARY_PHOTOS[2],
    source: "Owner Contact Finder",
    activity: "Contact found today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-2",
    address: "1402 E Lenoir St",
    locality: "Raleigh, NC 27601",
    photo: LIBRARY_PHOTOS[3],
    source: "Single address",
    activity: "Health checked today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-10",
    address: "67 Lakeshore Ct",
    locality: "Wake Forest, NC 27587",
    photo: LIBRARY_PHOTOS[4],
    source: "Owner Contact Finder",
    activity: "Snapshot complete",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-1",
    address: "193 Crossings Pl",
    locality: "Apex, NC 27502",
    photo: LIBRARY_PHOTOS[5],
    source: "Realtor.com profile",
    activity: "Imported 2 days ago",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-9",
    address: "412 Oakwood Dr",
    locality: "Chapel Hill, NC 27514",
    photo: LIBRARY_PHOTOS[6],
    source: "CRM import",
    activity: "Imported 4 days ago",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-7",
    address: "2318 North Sherman Williams Blvd",
    locality: "Raleigh, NC 27609",
    photo: LIBRARY_PHOTOS[7],
    source: "Zillow profile",
    activity: "Seller update ready",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-4",
    address: "789 Pine Ridge",
    locality: "Cary, NC 27513",
    photo: LIBRARY_PHOTOS[0],
    source: "CRM import",
    activity: "Imported last week",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-11",
    address: "1209 Brookline Way",
    locality: "Morrisville, NC 27560",
    photo: LIBRARY_PHOTOS[1],
    source: "Realtor.com profile",
    activity: "Marketing refreshed",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-6",
    address: "72 Grove Street",
    locality: "Clayton, NC 27520",
    photo: LIBRARY_PHOTOS[2],
    source: "CRM import",
    activity: "Contact linked today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-3",
    address: "555 Main St",
    locality: "Fuquay-Varina, NC 27526",
    photo: LIBRARY_PHOTOS[3],
    source: "Owner Contact Finder",
    activity: "Strategy started",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-13",
    address: "3101 Glenwood Ave",
    locality: "Raleigh, NC 27612",
    photo: LIBRARY_PHOTOS[4],
    source: "Zillow profile",
    activity: "Health checked today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-14",
    address: "1420 Hillsborough St",
    locality: "Raleigh, NC 27607",
    photo: LIBRARY_PHOTOS[5],
    source: "Realtor.com profile",
    activity: "Snapshot complete",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-15",
    address: "801 W Main St",
    locality: "Durham, NC 27701",
    photo: LIBRARY_PHOTOS[6],
    source: "CRM import",
    activity: "Imported 3 days ago",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-16",
    address: "2200 Lake Boone Trl",
    locality: "Raleigh, NC 27607",
    photo: LIBRARY_PHOTOS[7],
    source: "Owner Contact Finder",
    activity: "Contact found today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-17",
    address: "5010 Falls of Neuse Rd",
    locality: "Raleigh, NC 27609",
    photo: LIBRARY_PHOTOS[0],
    source: "Single address",
    activity: "Marketing refreshed",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-18",
    address: "108 Meadowbrook Dr",
    locality: "Cary, NC 27511",
    photo: LIBRARY_PHOTOS[1],
    source: "Zillow profile",
    activity: "Seller update ready",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-19",
    address: "3300 University Dr",
    locality: "Durham, NC 27707",
    photo: LIBRARY_PHOTOS[2],
    source: "Realtor.com profile",
    activity: "Imported last week",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-20",
    address: "45 Chapel Hill Rd",
    locality: "Carrboro, NC 27510",
    photo: LIBRARY_PHOTOS[3],
    source: "CRM import",
    activity: "Contact linked today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-21",
    address: "1800 Cameron St",
    locality: "Chapel Hill, NC 27514",
    photo: LIBRARY_PHOTOS[4],
    source: "Owner Contact Finder",
    activity: "Strategy started",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-22",
    address: "920 Kildaire Farm Rd",
    locality: "Cary, NC 27511",
    photo: LIBRARY_PHOTOS[5],
    source: "Single address",
    activity: "Health checked today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-23",
    address: "6100 Falls of Neuse Rd",
    locality: "Raleigh, NC 27609",
    photo: LIBRARY_PHOTOS[6],
    source: "Zillow profile",
    activity: "Closed last month",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-24",
    address: "1150 Holly Springs Rd",
    locality: "Holly Springs, NC 27540",
    photo: LIBRARY_PHOTOS[7],
    source: "Realtor.com profile",
    activity: "Snapshot complete",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-25",
    address: "3400 Six Forks Rd",
    locality: "Raleigh, NC 27609",
    photo: LIBRARY_PHOTOS[0],
    source: "CRM import",
    activity: "Imported 5 days ago",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-26",
    address: "88 Market St",
    locality: "Garner, NC 27529",
    photo: LIBRARY_PHOTOS[1],
    source: "Owner Contact Finder",
    activity: "Contact found today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-27",
    address: "2100 Ten Ten Rd",
    locality: "Apex, NC 27539",
    photo: LIBRARY_PHOTOS[2],
    source: "Single address",
    activity: "Marketing refreshed",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-28",
    address: "4500 Louisburg Rd",
    locality: "Raleigh, NC 27604",
    photo: LIBRARY_PHOTOS[3],
    source: "Zillow profile",
    activity: "Health checked today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-29",
    address: "1600 Capital Blvd",
    locality: "Raleigh, NC 27604",
    photo: LIBRARY_PHOTOS[4],
    source: "Realtor.com profile",
    activity: "Seller update ready",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-30",
    address: "7200 Creedmoor Rd",
    locality: "Raleigh, NC 27613",
    photo: LIBRARY_PHOTOS[5],
    source: "CRM import",
    activity: "Imported 2 days ago",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-31",
    address: "300 E Main St",
    locality: "Smithfield, NC 27577",
    photo: LIBRARY_PHOTOS[6],
    source: "Owner Contact Finder",
    activity: "Strategy started",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-32",
    address: "5500 Durham-Chapel Hill Blvd",
    locality: "Durham, NC 27707",
    photo: LIBRARY_PHOTOS[7],
    source: "Single address",
    activity: "Snapshot complete",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-33",
    address: "1200 Village Market Pl",
    locality: "Morrisville, NC 27560",
    photo: LIBRARY_PHOTOS[0],
    source: "Zillow profile",
    activity: "Contact linked today",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-34",
    address: "8900 Leesville Rd",
    locality: "Raleigh, NC 27613",
    photo: LIBRARY_PHOTOS[1],
    source: "Realtor.com profile",
    activity: "Imported last week",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-35",
    address: "2400 Wake Forest Rd",
    locality: "Raleigh, NC 27609",
    photo: LIBRARY_PHOTOS[2],
    source: "CRM import",
    activity: "Marketing refreshed",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-36",
    address: "4100 New Bern Ave",
    locality: "Raleigh, NC 27610",
    photo: LIBRARY_PHOTOS[3],
    source: "Owner Contact Finder",
    activity: "Health checked today",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-37",
    address: "1500 N Main St",
    locality: "Fuquay-Varina, NC 27526",
    photo: LIBRARY_PHOTOS[4],
    source: "Single address",
    activity: "Closed last month",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-38",
    address: "6200 Falls River Ave",
    locality: "Raleigh, NC 27614",
    photo: LIBRARY_PHOTOS[5],
    source: "Zillow profile",
    activity: "Seller update ready",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-39",
    address: "330 W Franklin St",
    locality: "Chapel Hill, NC 27516",
    photo: LIBRARY_PHOTOS[6],
    source: "Realtor.com profile",
    activity: "Imported 4 days ago",
    hasBuyer: false,
    hasSeller: true,
  },
  {
    id: "lib-40",
    address: "1800 Walnut Creek Pkwy",
    locality: "Raleigh, NC 27606",
    photo: LIBRARY_PHOTOS[7],
    source: "CRM import",
    activity: "Contact found today",
    hasBuyer: true,
    hasSeller: true,
  },
  {
    id: "lib-41",
    address: "9500 Strickland Rd",
    locality: "Raleigh, NC 27615",
    photo: LIBRARY_PHOTOS[0],
    source: "Owner Contact Finder",
    activity: "Snapshot complete",
    hasBuyer: true,
    hasSeller: false,
  },
  {
    id: "lib-42",
    address: "2700 NC Hwy 55",
    locality: "Apex, NC 27502",
    photo: LIBRARY_PHOTOS[1],
    source: "Single address",
    activity: "Strategy started",
    hasBuyer: false,
    hasSeller: true,
  },
];

const BRAND_SOURCE_ICONS = {
  zillow: "../assets/Zillow_idPQmSoeCk_0.svg",
  realtor: "../assets/Realtor-com_id_S0YERJE_1.svg",
  redfin: "../assets/Redfin_idhndHECHp_0.svg",
};

const DAKLAB_TOOL_SOURCES = [
  { match: "owner contact", icon: LibraryIcon.contact },
  { match: "property snapshot", icon: LibraryIcon.snapshot },
  { match: "listing strategy", icon: LibraryIcon.list },
  { match: "marketing refresh", icon: LibraryIcon.refresh },
  { match: "seller update", icon: LibraryIcon.trend },
  { match: "contact enrichment", icon: LibraryIcon.search },
];

function BrandSourceIcon({ src }) {
  return <img className="home-source-brand" src={src} alt="" />;
}

function resolveSourceIcon(source) {
  const lower = source.toLowerCase();
  if (lower.includes("zillow")) return <BrandSourceIcon src={BRAND_SOURCE_ICONS.zillow} />;
  if (lower.includes("realtor")) return <BrandSourceIcon src={BRAND_SOURCE_ICONS.realtor} />;
  if (lower.includes("redfin")) return <BrandSourceIcon src={BRAND_SOURCE_ICONS.redfin} />;
  for (const { match, icon } of DAKLAB_TOOL_SOURCES) {
    if (lower.includes(match)) return icon;
  }
  return null;
}

function PropertySourceCell({ source }) {
  return (
    <td className="home-table-source">
      <div className="home-table-source-cell">
        <span className="home-table-source-icon" aria-hidden="true">
          {resolveSourceIcon(source)}
        </span>
        <span className="home-table-source-text">{source}</span>
      </div>
    </td>
  );
}

function RepresentingCell({ hasBuyer, hasSeller }) {
  if (hasBuyer && hasSeller) {
    return (
      <td>
        <div className="home-table-btn-split">
          <a href={TEMP_BUYER_HREF} className="home-table-btn-ghost">
            Buyer
          </a>
          <a href={TEMP_SELLER_HREF} className="home-table-btn-ghost">
            Seller
          </a>
        </div>
      </td>
    );
  }

  const label = hasBuyer ? "Buyer" : "Seller";
  const href = hasBuyer ? TEMP_BUYER_HREF : TEMP_SELLER_HREF;

  return (
    <td>
      <a href={href} className="home-table-btn-ghost">
        {label}
      </a>
    </td>
  );
}

function LibraryPager({ page, totalPages, onPageChange }) {
  return (
    <div className="home-library-pager" aria-label="Property library pagination">
      <button
        type="button"
        className="home-library-pager-btn"
        aria-label="Previous page"
        disabled={page <= 1}
        onClick={() => onPageChange(page - 1)}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M15 18l-6-6 6-6"/>
        </svg>
      </button>
      <span className="home-library-pager-num">{page}</span>
      <button
        type="button"
        className="home-library-pager-btn"
        aria-label="Next page"
        disabled={page >= totalPages}
        onClick={() => onPageChange(page + 1)}
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M9 18l6-6-6-6"/>
        </svg>
      </button>
    </div>
  );
}

function PropertyLibrary() {
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(1);

  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 totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));

  useEffect(() => {
    setPage(1);
  }, [query]);

  useEffect(() => {
    if (page > totalPages) setPage(totalPages);
  }, [page, totalPages]);

  const pageRows = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  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">
            {LibraryIcon.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 home-library-scroll-paged">
          <table className="home-table">
            <thead>
              <tr>
                <th className="home-table-property-head">
                  <div className="home-table-property-head-inner">
                    <span
                      className="home-table-property-head-spacer"
                      aria-hidden="true"
                    />
                    <span className="home-table-property-head-label">
                      Property
                    </span>
                  </div>
                </th>
                <th>Source</th>
                <th>Last Activity</th>
                <th>Active workflows</th>
                <th style={{ textAlign: "right" }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {pageRows.map(row => (
                <tr key={row.id}>
                  <td className="home-table-property">
                    <div className="home-table-property-inner">
                      <div className="home-table-addr">
                        <div>
                          <a
                            href={TEMP_DETAILS_HREF}
                            className="home-temp-ph-link"
                          >
                            {row.address}
                          </a>
                        </div>
                        {row.locality && (
                          <div className="home-table-locality">
                            {row.locality}
                          </div>
                        )}
                      </div>
                      <div className="home-table-thumb-slot" aria-hidden="true">
                        {row.photo && <img src={row.photo} alt="" />}
                      </div>
                    </div>
                  </td>
                  <PropertySourceCell source={row.source} />
                  <td className="home-table-activity">{row.activity}</td>
                  <RepresentingCell
                    hasBuyer={row.hasBuyer}
                    hasSeller={row.hasSeller}
                  />
                  <td style={{ textAlign: "right" }}>
                    <div
                      className="home-table-actions"
                      style={{ justifyContent: "flex-end" }}
                    >
                      <a
                        href={TEMP_DETAILS_HREF}
                        className="home-table-btn"
                      >
                        Details
                      </a>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="home-library-foot">
            <LibraryPager page={page} totalPages={totalPages} onPageChange={setPage} />
          </div>
        </div>
      )}
    </section>
  );
}

window.PropertyLibrary = PropertyLibrary;
