const { escapeHtml, cleanRichText, bytes } = require("./utils");

function setting(settings, key, fallback = "") {
  return settings[key] ?? fallback;
}

function publicLayout({ title, description, settings, nav = [], body, csrfToken = "", currentPath = "", extraHead = "" }) {
  const business = setting(settings, "business.name", "Debbie Windler Seamstress");
  const theme = themeVars(settings);
  const navHtml = nav.map((link) => `
    <a class="${currentPath === link.url ? "active" : ""}" href="${escapeHtml(link.url)}" ${link.opens_new_tab ? 'target="_blank" rel="noopener noreferrer"' : ""}>${escapeHtml(link.label)}</a>
  `).join("");
  return `<!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>${escapeHtml(title || setting(settings, "site.title", business))}</title>
    <meta name="description" content="${escapeHtml(description || setting(settings, "site.description", ""))}">
    <meta property="og:title" content="${escapeHtml(title || business)}">
    <meta property="og:description" content="${escapeHtml(description || setting(settings, "site.description", ""))}">
    <meta property="og:type" content="website">
    <meta name="theme-color" content="${escapeHtml(setting(settings, "theme.button", "#7d3f45"))}">
    <link rel="stylesheet" href="/css/site.css">
    <style>:root{${theme}}</style>
    ${extraHead}
  </head>
  <body>
    <a class="skip-link" href="#main">Skip to content</a>
    <header class="site-header">
      <a class="brand" href="/" aria-label="${escapeHtml(business)} home">
        <span class="brand-mark" aria-hidden="true"></span>
        <span>${escapeHtml(business)}</span>
      </a>
      <button class="menu-toggle" data-menu-toggle aria-expanded="false" aria-controls="site-menu">Menu</button>
      <nav id="site-menu" class="site-nav" aria-label="Main navigation">
        ${navHtml}
        <a class="nav-cta" href="/about-contact#contact-form">Contact Debbie</a>
      </nav>
    </header>
    <main id="main">${body}</main>
    <footer class="site-footer">
      <div>
        <strong>${escapeHtml(business)}</strong>
        <p>${escapeHtml(setting(settings, "business.footer_text", ""))}</p>
      </div>
      <div>
        ${contactLine(settings)}
        <p>${escapeHtml(setting(settings, "business.hours", "By appointment"))}</p>
      </div>
      <nav aria-label="Footer navigation">${navHtml}</nav>
      <p class="copyright">&copy; ${new Date().getFullYear()} ${escapeHtml(business)}. ${escapeHtml(setting(settings, "business.copyright", "All rights reserved."))}</p>
    </footer>
    <form hidden method="post"><input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}"></form>
    <script src="/js/site.js" defer></script>
  </body>
  </html>`;
}

function adminLayout({ title, body, admin, csrfToken, active = "" }) {
  const menu = [
    ["dashboard", "Dashboard", "/admin/dashboard"],
    ["home", "Home Page", "/admin/home"],
    ["pages", "Pages", "/admin/pages"],
    ["items", "Items", "/admin/items"],
    ["services", "Services", "/admin/services"],
    ["about", "About and Equipment", "/admin/about-equipment"],
    ["messages", "Messages", "/admin/messages"],
    ["media", "Media Library", "/admin/media"],
    ["appearance", "Appearance", "/admin/appearance"],
    ["navigation", "Navigation", "/admin/navigation"],
    ["business", "Business Settings", "/admin/business"],
    ["seo", "Search and Sharing", "/admin/seo"],
    ["security", "Security", "/admin/security"],
    ["backups", "Backups", "/admin/backups"],
    ["maintenance", "Maintenance", "/admin/maintenance"]
  ];
  const menuHtml = menu.map(([key, label, url]) => `<a class="${active === key ? "active" : ""}" href="${url}">${label}</a>`).join("");
  return `<!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>${escapeHtml(title)} - Owner Area</title>
    <link rel="stylesheet" href="/css/admin.css">
  </head>
  <body>
    <a class="skip-link" href="#admin-main">Skip to content</a>
    <aside class="admin-sidebar">
      <a class="admin-brand" href="/admin/dashboard">Debbie Windler<br><span>Owner Area</span></a>
      <nav aria-label="Owner area">${menuHtml}</nav>
      <a href="/" target="_blank" rel="noopener noreferrer">Preview Website</a>
      <form method="post" action="/admin/logout">
        <input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}">
        <button type="submit" class="link-button">Log Out</button>
      </form>
    </aside>
    <main id="admin-main" class="admin-main">
      <header class="admin-top">
        <div>
          <p class="eyebrow">Owner administration</p>
          <h1>${escapeHtml(title)}</h1>
        </div>
        <p class="admin-user">${escapeHtml(admin?.name || "")}</p>
      </header>
      ${body}
    </main>
    <script src="/js/admin.js" defer></script>
  </body>
  </html>`;
}

function authLayout(title, body) {
  return `<!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>${escapeHtml(title)} - Debbie Windler Seamstress</title>
    <link rel="stylesheet" href="/css/admin.css">
  </head>
  <body class="auth-page">
    <main class="auth-card">
      <h1>${escapeHtml(title)}</h1>
      ${body}
    </main>
  </body>
  </html>`;
}

function themeVars(settings) {
  const keys = {
    "--bg": ["theme.bg", "#fffaf5"],
    "--bg-alt": ["theme.bg_alt", "#f4e8df"],
    "--text": ["theme.text", "#342b28"],
    "--heading": ["theme.heading", "#2d2522"],
    "--link": ["theme.link", "#7d3f45"],
    "--button": ["theme.button", "#7d3f45"],
    "--button-text": ["theme.button_text", "#ffffff"],
    "--accent": ["theme.accent", "#7a8f73"],
    "--radius": ["theme.radius", "8"],
    "--site-width": ["theme.width", "1120"]
  };
  const css = Object.entries(keys).map(([name, [key, fallback]]) => `${name}:${escapeHtml(setting(settings, key, fallback))}${name === "--radius" || name === "--site-width" ? "px" : ""};`);
  css.push(`--heading-font:${escapeHtml(setting(settings, "theme.heading_font", "Georgia, 'Times New Roman', serif"))};`);
  css.push(`--body-font:${escapeHtml(setting(settings, "theme.body_font", "Arial, Helvetica, sans-serif"))};`);
  return css.join("");
}

function contactLine(settings) {
  const email = setting(settings, "business.email", "");
  const phone = setting(settings, "business.phone", "");
  const facebook = setting(settings, "business.facebook", "");
  return `
    ${email ? `<p><a href="mailto:${escapeHtml(email)}">${escapeHtml(email)}</a></p>` : ""}
    ${phone ? `<p><a href="tel:${escapeHtml(phone)}">${escapeHtml(phone)}</a></p>` : ""}
    ${facebook ? `<p><a href="${escapeHtml(facebook)}" target="_blank" rel="noopener noreferrer">Facebook</a></p>` : ""}
  `;
}

function button(label, href, className = "button") {
  if (!label || !href) return "";
  return `<a class="${className}" href="${escapeHtml(href)}">${escapeHtml(label)}</a>`;
}

function itemCard(item) {
  const badgeBits = [item.newly_added ? "New" : "", item.on_sale ? "Sale" : "", item.availability_status].filter(Boolean);
  return `<article class="item-card">
    ${item.image_url ? `<img src="${escapeHtml(item.image_url)}" alt="${escapeHtml(item.image_alt || item.name)}" loading="lazy">` : `<div class="image-placeholder" aria-hidden="true"></div>`}
    <div class="card-body">
      <div class="badges">${badgeBits.map((badge) => `<span>${escapeHtml(badge)}</span>`).join("")}</div>
      <h3><a href="/items/${escapeHtml(item.slug)}">${escapeHtml(item.name)}</a></h3>
      <p>${escapeHtml(item.short_description || "")}</p>
      <p class="price">${priceText(item)}</p>
      <div class="card-actions">
        ${button("View Details", `/items/${item.slug}`, "text-button")}
        ${button("Ask About This Item", `/about-contact?item=${encodeURIComponent(item.name)}#contact-form`, "button small")}
      </div>
    </div>
  </article>`;
}

function serviceCard(service) {
  return `<article class="service-card">
    ${service.image_url ? `<img src="${escapeHtml(service.image_url)}" alt="${escapeHtml(service.image_alt || service.name)}" loading="lazy">` : `<div class="image-placeholder thread" aria-hidden="true"></div>`}
    <div class="card-body">
      <h3>${escapeHtml(service.name)}</h3>
      <p>${escapeHtml(service.short_description || "")}</p>
      ${service.pricing_note ? `<p class="pricing-note">${escapeHtml(service.pricing_note)}</p>` : ""}
      ${button("Ask About This Service", `/about-contact?service=${encodeURIComponent(service.name)}#contact-form`, "button small")}
    </div>
  </article>`;
}

function priceText(item) {
  if (item.contact_for_pricing) return "Contact for pricing";
  if (item.price_range) return escapeHtml(item.price_range);
  if (item.starting_price) return `Starting at ${escapeHtml(item.starting_price)}`;
  if (item.price) return escapeHtml(item.price);
  return "";
}

function contactForm({ csrfToken, item = "", service = "", success = false, settings = {} }) {
  return `<section id="contact-form" class="contact-form-section">
    <div class="section-heading">
      <p class="eyebrow">Contact</p>
      <h2>Contact Debbie</h2>
      <p>${escapeHtml(setting(settings, "business.preferred_contact", "Email or the website form are preferred."))}</p>
      ${success ? `<p class="notice success" role="status">Thank you. Your message was saved and Debbie will be notified if email is configured.</p>` : ""}
    </div>
    <form class="contact-form" method="post" action="/contact" novalidate>
      <input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}">
      <input type="hidden" name="source_page" value="/about-contact">
      <label class="hp">Leave this field empty <input type="text" name="website"></label>
      <label>Name <input required maxlength="120" name="name" autocomplete="name"></label>
      <label>Email <input required maxlength="180" type="email" name="email" autocomplete="email"></label>
      <label>Phone, optional <input maxlength="80" name="phone" autocomplete="tel"></label>
      <label>Preferred contact method
        <select name="preferred_contact">
          <option>Email</option>
          <option>Phone</option>
          <option>Text message</option>
        </select>
      </label>
      <label>Subject <input required maxlength="160" name="subject" value="${escapeHtml(item ? `Question about ${item}` : service ? `Question about ${service}` : "")}"></label>
      <label>Item or service being discussed <input maxlength="160" name="related" value="${escapeHtml(item || service)}"></label>
      <label>Message <textarea required maxlength="3000" name="message" rows="7"></textarea></label>
      <label class="checkbox"><input type="checkbox" required name="consent" value="1"> I understand this information will be used to answer my inquiry.</label>
      <button type="submit">Send Message</button>
    </form>
  </section>`;
}

function sectionHtml(section) {
  if (!section.is_published) return "";
  const style = [
    section.background_color ? `background-color:${escapeHtml(section.background_color)}` : "",
    section.background_url ? `background-image:url('${escapeHtml(section.background_url)}')` : ""
  ].filter(Boolean).join(";");
  const image = section.image_url ? `<img src="${escapeHtml(section.image_url)}" alt="${escapeHtml(section.image_alt || section.title || "")}" loading="lazy">` : "";
  const content = `<div class="section-copy">
    ${section.title ? `<h2>${escapeHtml(section.title)}</h2>` : ""}
    ${cleanRichText(section.body || "")}
    ${button(section.button_label, section.button_url)}
  </div>`;
  if (section.layout === "image-left") return `<section class="content-section split" style="${style}">${image}${content}</section>`;
  if (section.layout === "image-right") return `<section class="content-section split reverse" style="${style}">${content}${image}</section>`;
  if (section.layout === "full-image") return `<section class="content-section full-image" style="${style}">${image}${content}</section>`;
  if (section.layout === "contact-callout") return `<section class="content-section contact-callout" style="${style}">${content}</section>`;
  return `<section class="content-section" style="${style}">${content}</section>`;
}

function mediaOption(media, selected) {
  return `<option value="${media.id}" ${Number(selected) === Number(media.id) ? "selected" : ""}>${escapeHtml(media.title || media.original_name)}</option>`;
}

function mediaGrid(media) {
  return `<div class="media-grid">${media.map((m) => `
    <article class="media-card">
      <img src="${escapeHtml(m.thumb_url || m.url)}" alt="${escapeHtml(m.alt_text || m.title || "")}">
      <strong>${escapeHtml(m.title || m.original_name)}</strong>
      <small>${escapeHtml(m.mime_type)} · ${bytes(m.size_bytes || 0)} ${m.width ? `· ${m.width}x${m.height}` : ""}</small>
    </article>
  `).join("")}</div>`;
}

module.exports = {
  publicLayout,
  adminLayout,
  authLayout,
  setting,
  button,
  itemCard,
  serviceCard,
  priceText,
  contactForm,
  sectionHtml,
  mediaOption,
  mediaGrid
};
