"use client";
import { useEffect, useState } from "react";
import AboutSection from "../about-section";
import CompanyBrand from "../company-brand";
export default function PublicProfile({ username }: { username: string }) {
  const [p, setP] = useState<any>(null),
    [view, setView] = useState("home"),
    [form, setForm] = useState<any>(null),
    [done, setDone] = useState(""),
    [manageMode, setManageMode] = useState<"" | "reschedule">(""),
    [contactDone, setContactDone] = useState("");
  useEffect(() => {
    fetch("/api/public/" + username)
      .then((r) => r.json())
      .then((d) => setP(d.profile || false));
  }, [username]);
  const track = (event: string, target = "") => {
    let visitorId = localStorage.getItem("mypagee-visitor");
    if (!visitorId) {
      visitorId = crypto.randomUUID();
      localStorage.setItem("mypagee-visitor", visitorId);
    }
    fetch(`/api/public/${username}/analytics`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        event,
        target,
        visitorId,
        source: document.referrer || "Direct",
      }),
    }).catch(() => {});
  };
  useEffect(() => {
    track("profile_view");
    if (new URLSearchParams(location.search).get("src") === "qr")
      track("qr_scan");
  }, [username]);
  if (p === null) return <main className="publicstate">Loading profile…</main>;
  if (!p)
    return (
      <main className="publicstate">
        This mypag.ee profile is not available.
      </main>
    );
  const send = async (e: any) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.currentTarget));
    const d = await fetch("/api/public/" + username, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ kind: form.kind, data }),
    }).then((r) => r.json());
    if (d.deliveryUrl)
      setForm((current: any) => ({ ...current, deliveryUrl: d.deliveryUrl }));
    if (d.autoReply)
      setForm((current: any) => ({ ...current, autoReply: d.autoReply }));
    if (form.kind === "booking")
      setForm((current: any) => ({ ...current, bookingData: data }));
    if (form.kind === "order") track("order_submit", form.item || "");
    setDone(d.reference || "Sent");
  };
  const manageBooking = async (
    action: "cancel" | "reschedule",
    data: any = {},
  ) => {
    const d = await fetch("/api/public/" + username, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ kind: "booking", action, reference: done, data }),
    }).then((r) => r.json());
    if (d.ok) {
      setManageMode("");
      setDone(action === "cancel" ? "Booking cancelled" : d.reference || done);
    }
  };
  const sendContact = async (e: any) => {
    e.preventDefault();
    const el = e.currentTarget,
      data = Object.fromEntries(new FormData(el));
    const d = await fetch("/api/public/" + username, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ kind: "contact", data }),
    }).then((r) => r.json());
    if (d.reference) {
      setContactDone(d.reference);
      el.reset();
    }
  };
  const builder = p.builder || {
      menuOrder: ["home", "vcard", "shop", "services", "about"],
      accentColor: "",
      font: "modern",
      buttonStyle: "rounded",
    },
    menuOrder = builder.menuOrder?.length
      ? builder.menuOrder
      : Object.keys(p.menus),
    now = Date.now(),
    activeLinks = (p.links || []).filter(
      (x: any) =>
        (!x.startAt || new Date(x.startAt).getTime() <= now) &&
        (!x.endAt || new Date(x.endAt).getTime() >= now),
    );
  return (
    <main className="publicwrap exactpublic">
      <TrackingScripts tracking={p.tracking} />
      <section
        className={`preview design t${p.theme} ${p.profileType} font-${builder.font} buttons-${builder.buttonStyle}`}
        style={
          builder.accentColor
            ? ({ "--a": builder.accentColor } as any)
            : undefined
        }
      >
        <div className="pcover">
          {p.coverUrl && <img src={p.coverUrl} alt="" />}
        </div>
        <div className="pavatar">
          {p.avatarUrl ? (
            <img src={p.avatarUrl} alt={p.name} />
          ) : (
            p.name.slice(0, 2).toUpperCase()
          )}
        </div>
        <h2>
          {p.name}
          {isPro(p) && (
            <i className="uil uil-award premiumbadge" title="mypag.ee Pro" />
          )}
        </h2>
        <b>{p.title}</b>
        <p>{p.bio}</p>
        <small>
          {p.category} · {p.location}
        </small>
        <CompanyBrand p={p} />
        <nav className="previewnav">
          {menuOrder
            .filter((k: string) => p.menus[k])
            .map((k: string) => (
              <button
                key={k}
                className={view === k ? "on" : ""}
                onClick={() => setView(k)}
              >
                {k}
              </button>
            ))}
        </nav>
        <div className="socialicons">
          {(p.socials || []).map((x: any, i: number) => (
            <a
              href={x.url}
              key={i}
              title={x.platform}
              onClick={() => track("link_click", x.platform)}
            >
              <i className={"uil " + x.icon} />
            </a>
          ))}
        </div>
        {view === "home" && (
          <>
            <div className="plinks">
              {activeLinks.map((x: any, i: number) => (
                <a
                  className={x.featured ? "featuredlink" : ""}
                  href={x.url}
                  key={i}
                  onClick={() => track("link_click", x.title)}
                >
                  {x.thumbnailUrl ? (
                    <img src={x.thumbnailUrl} alt="" />
                  ) : (
                    <i className={"uil " + (x.icon || "uil-link")} />
                  )}
                  <b>{x.title}</b>
                  <span>↗</span>
                </a>
              ))}
            </div>
            <HomeActions p={p} track={track} />
            {p.booking?.enabled && (
              <div className="direct-booking-card">
                <span>
                  <i className="uil uil-calendar-alt" />
                </span>
                <div>
                  <b>{p.booking.title}</b>
                  <small>
                    {p.booking.duration} min ·{" "}
                    {p.booking.priceType === "paid" && p.booking.price
                      ? `৳${p.booking.price}`
                      : "Free"}
                  </small>
                  <p>{p.booking.description}</p>
                </div>
                <button
                  onClick={() =>
                    setForm({
                      kind: "booking",
                      bookingType: "direct",
                      title: p.booking.title,
                      item: p.booking.title,
                      ...p.booking,
                    })
                  }
                >
                  Book now
                </button>
              </div>
            )}
            <LeadActions p={p} setForm={setForm} track={track} />
          </>
        )}
        {view === "vcard" && (
          <>
            <div className="contacts">
              {p.phones.map((x: any, i: number) => (
                <span key={"p" + i}>
                  <i className="uil uil-phone" /> {x.label}: {x.value}
                </span>
              ))}
              {(p.whatsapps || []).map((x: any, i: number) => (
                <span key={"wa" + i}>
                  <i className="uil uil-whatsapp" /> {x.label}: {x.value}
                </span>
              ))}
              {p.emails.map((x: any, i: number) => (
                <span key={"e" + i}>
                  <i className="uil uil-envelope" /> {x.label}: {x.value}
                </span>
              ))}
              {p.websites.map((x: any, i: number) => (
                <span key={"w" + i}>
                  <i className="uil uil-globe" /> {x.label}: {x.value}
                </span>
              ))}
            </div>
            <VCardButton p={p} track={track} />
            <form
              className="vcard-contact-form inline-contact-form"
              onSubmit={sendContact}
            >
              <i className="uil uil-comment-alt-lines" />
              <h3>Contact {p.name}</h3>
              <p>Send a message directly from this profile.</p>
              {contactDone ? (
                <div className="contact-success">
                  <i className="uil uil-check-circle" />
                  <b>Message sent</b>
                  <small>Reference: {contactDone}</small>
                  <button type="button" onClick={() => setContactDone("")}>
                    Send another message
                  </button>
                </div>
              ) : (
                <>
                  <label>
                    Your name
                    <input name="name" required placeholder="Full name" />
                  </label>
                  <label>
                    Phone / WhatsApp
                    <input name="phone" required placeholder="Your number" />
                  </label>
                  <label>
                    Email <small>(optional)</small>
                    <input
                      name="email"
                      type="email"
                      placeholder="you@example.com"
                    />
                  </label>
                  <label>
                    Message
                    <textarea
                      name="message"
                      required
                      placeholder="Write your message"
                    />
                  </label>
                  <button className="publicaction">
                    <i className="uil uil-message" /> Send message
                  </button>
                </>
              )}
            </form>
          </>
        )}
        {view === "shop" && (
          <div className="previewitems">
            {p.products.map((x: any) => {
              const soldOut = x.trackStock && Number(x.stock) <= 0,
                mode = x.checkoutMode || "both",
                wa = (
                  p.whatsapps?.[0]?.value ||
                  p.phones?.[0]?.value ||
                  ""
                ).replace(/[^0-9]/g, ""),
                message = encodeURIComponent(
                  `Hello, I want to order ${x.name}${x.price ? ` — ৳${x.price}` : ""}. Product ID: ${x.id}`,
                );
              return (
                <article key={x.id} className={soldOut ? "soldout" : ""}>
                  {x.imageUrl ? <img src={x.imageUrl} alt={x.name} /> : <i />}
                  <span className="storetype">
                    <i
                      className={
                        x.itemType === "course"
                          ? "uil uil-graduation-cap"
                          : x.itemType === "digital"
                            ? "uil uil-file-download"
                            : "uil uil-box"
                      }
                    />
                    {x.itemType || "physical"}
                  </span>
                  <b>{x.name}</b>
                  <small>{x.description}</small>
                  {x.price && x.showPrice !== false && (
                    <strong>৳{x.price}</strong>
                  )}
                  {x.trackStock && (
                    <small className="stocknote">
                      {soldOut ? "Out of stock" : `${x.stock} available`}
                    </small>
                  )}
                  <div className="storeactions">
                    {mode !== "whatsapp" && (
                      <button
                        disabled={soldOut}
                        onClick={() => {
                          track("product_view", x.name);
                          setForm({
                            kind: "order",
                            title: "Order " + x.name,
                            item: x.name,
                            itemType: x.itemType,
                            variants: x.variants,
                          });
                        }}
                      >
                        <i className="uil uil-shopping-bag" />{" "}
                        {soldOut ? "Sold out" : "Checkout"}
                      </button>
                    )}
                    {mode !== "direct" && wa && (
                      <a
                        className="waorder"
                        href={`https://wa.me/${wa}?text=${message}`}
                        target="_blank"
                        onClick={() => track("whatsapp_click", x.name)}
                      >
                        <i className="uil uil-whatsapp" /> WhatsApp
                      </a>
                    )}
                  </div>
                </article>
              );
            })}
          </div>
        )}
        {view === "services" && (
          <div className="previewservices">
            {p.services.map((x: any) => (
              <article key={x.id}>
                {x.imageUrl ? (
                  <img src={x.imageUrl} alt={x.name} />
                ) : (
                  <span>
                    <i className="uil uil-briefcase-alt" />
                  </span>
                )}
                <div>
                  <b>{x.name}</b>
                  <small>{x.description}</small>
                  {x.duration && (
                    <small>
                      {x.duration} min ·{" "}
                      {x.bookingPriceType === "paid" && x.price
                        ? `৳${x.price}`
                        : "Free booking"}
                    </small>
                  )}
                </div>
                {x.bookingEnabled !== false && (
                  <button
                    onClick={() =>
                      setForm({
                        kind: "booking",
                        bookingType: "service",
                        title: "Book " + x.name,
                        item: x.name,
                        priceType: x.bookingPriceType || "free",
                        price: x.price,
                        duration: x.duration || "30",
                        dateTimeOptional: x.dateTimeOptional !== false,
                        availableSchedule: x.availableSchedule,
                        meetingProvider: x.meetingProvider,
                        meetingLink: x.meetingLink,
                        reminder: x.bookingReminder,
                        consultationQuestions: x.consultationQuestions,
                      })
                    }
                  >
                    Book
                  </button>
                )}
              </article>
            ))}
          </div>
        )}
        {view === "about" && <AboutSection p={p} />}
        <PublicAd p={p} />
        <footer>Made with mypag.ee/{p.username || "username"}</footer>
      </section>
      <ContactActions p={p} track={track} />
      {form && (
        <div className="publicmodal">
          <form onSubmit={send}>
            {done ? (
              <>
                <h2>✓ Request received</h2>
                <p>
                  Reference: <b>{done}</b>
                </p>
                {form.autoReply && (
                  <div className="autoreply">
                    <b>{form.autoReply.subject}</b>
                    <p>{form.autoReply.message}</p>
                  </div>
                )}
                {form.kind === "booking" && done !== "Booking cancelled" && (
                  <>
                    {form.bookingData?.date && (
                      <a
                        className="calendarlink"
                        href={googleCalendarUrl(form)}
                        target="_blank"
                      >
                        <i className="uil uil-google" /> Add to Google Calendar
                      </a>
                    )}
                    {form.meetingLink && (
                      <a
                        className="meetinglink"
                        href={form.meetingLink}
                        target="_blank"
                      >
                        <i className="uil uil-video" /> Open{" "}
                        {form.meetingProvider === "zoom"
                          ? "Zoom"
                          : form.meetingProvider === "google-meet"
                            ? "Google Meet"
                            : "meeting details"}
                      </a>
                    )}
                    {form.reminder && form.reminder !== "None" && (
                      <small className="bookingnote">
                        <i className="uil uil-bell" /> Reminder: {form.reminder}
                      </small>
                    )}
                    <div className="managebooking">
                      <button
                        type="button"
                        onClick={() => setManageMode("reschedule")}
                      >
                        Reschedule
                      </button>
                      <button
                        type="button"
                        className="cancelbooking"
                        onClick={() => manageBooking("cancel")}
                      >
                        Cancel booking
                      </button>
                    </div>
                    {manageMode === "reschedule" && (
                      <div className="reschedulebox">
                        <input id="new-booking-date" type="date" />
                        <input id="new-booking-time" type="time" />
                        <button
                          type="button"
                          onClick={() =>
                            manageBooking("reschedule", {
                              date: (
                                document.getElementById(
                                  "new-booking-date",
                                ) as HTMLInputElement
                              )?.value,
                              time: (
                                document.getElementById(
                                  "new-booking-time",
                                ) as HTMLInputElement
                              )?.value,
                            })
                          }
                        >
                          Confirm new time
                        </button>
                      </div>
                    )}
                  </>
                )}
                {form.deliveryUrl && (
                  <a
                    className="digitaldelivery"
                    href={form.deliveryUrl}
                    target="_blank"
                  >
                    <i className="uil uil-file-download" /> Access your digital
                    product
                  </a>
                )}
                <button
                  type="button"
                  onClick={() => {
                    setForm(null);
                    setDone("");
                  }}
                >
                  Done
                </button>
              </>
            ) : (
              <>
                <h2>{form.title}</h2>
                <input name="item" type="hidden" value={form.item || ""} />
                <label>
                  Name
                  <input name="name" required={form.kind !== "subscriber"} />
                </label>
                <label>
                  Phone / WhatsApp
                  <input
                    name="phone"
                    required={form.kind === "lead" || form.kind === "inquiry"}
                  />
                </label>
                <label>
                  Email
                  <input
                    name="email"
                    type="email"
                    required={form.kind === "subscriber"}
                  />
                </label>
                {form.kind === "order" && (
                  <>
                    {form.variants && (
                      <label>
                        Variant
                        <select name="variant" required>
                          <option value="">Select</option>
                          {form.variants.split(",").map((v: string) => (
                            <option key={v.trim()}>{v.trim()}</option>
                          ))}
                        </select>
                      </label>
                    )}
                    <label>
                      Quantity
                      <input
                        name="quantity"
                        type="number"
                        min="1"
                        defaultValue="1"
                        required
                      />
                    </label>
                    <label>
                      Delivery address{" "}
                      {form.itemType !== "physical" && (
                        <small>(optional)</small>
                      )}
                      <textarea
                        name="address"
                        required={
                          form.itemType === "physical" || !form.itemType
                        }
                      />
                    </label>
                    <label>
                      Coupon code <small>(optional)</small>
                      <input name="coupon" />
                    </label>
                  </>
                )}
                {form.kind === "booking" && (
                  <>
                    <input
                      name="bookingType"
                      type="hidden"
                      value={form.bookingType || "service"}
                    />
                    <input
                      name="duration"
                      type="hidden"
                      value={form.duration || "30"}
                    />
                    {form.availableSchedule && (
                      <div className="schedulehint">
                        <i className="uil uil-clock" />
                        <span>
                          <b>Available schedule</b>
                          {form.availableSchedule}
                        </span>
                      </div>
                    )}
                    <label>
                      Date{" "}
                      {form.dateTimeOptional !== false && (
                        <small>(optional)</small>
                      )}
                      <input
                        name="date"
                        type="date"
                        required={form.dateTimeOptional === false}
                      />
                    </label>
                    <label>
                      Time{" "}
                      {form.dateTimeOptional !== false && (
                        <small>(optional)</small>
                      )}
                      <input
                        name="time"
                        type="time"
                        required={form.dateTimeOptional === false}
                      />
                    </label>
                    {form.priceType === "paid" && form.price && (
                      <div className="bookingprice">
                        <span>Booking fee</span>
                        <b>৳{form.price}</b>
                      </div>
                    )}
                    {form.consultationQuestions && (
                      <label>
                        Consultation details
                        <textarea
                          name="consultation"
                          placeholder={form.consultationQuestions}
                        />
                      </label>
                    )}
                  </>
                )}
                <label>
                  Message
                  <textarea name="message" />
                </label>
                <button>Submit</button>
                <button
                  type="button"
                  className="cancel"
                  onClick={() => setForm(null)}
                >
                  Cancel
                </button>
              </>
            )}
          </form>
        </div>
      )}
    </main>
  );
}
function LeadActions({
  p,
  setForm,
  track,
}: {
  p: any;
  setForm: (value: any) => void;
  track: (event: string, target?: string) => void;
}) {
  const s = {
    shareContact: true,
    inquiry: true,
    appointment: true,
    whatsappLead: true,
    subscriber: true,
    ...(p.leadSettings || {}),
  };
  const wa = (p.whatsapps?.[0]?.value || p.phones?.[0]?.value || "").replace(
    /[^0-9]/g,
    "",
  );
  const actions = [
    s.shareContact && {
      key: "lead",
      icon: "uil-exchange",
      title: "Share your contact with me",
      text: "Send your contact details securely",
    },
    s.inquiry && {
      key: "inquiry",
      icon: "uil-comment-question",
      title: "Send an inquiry",
      text: "Ask a question or request information",
    },
    s.appointment && {
      key: "booking",
      icon: "uil-calendar-alt",
      title: "Request an appointment",
      text: "Request a date and time",
    },
    s.subscriber && {
      key: "subscriber",
      icon: "uil-envelope-add",
      title: "Get updates",
      text: "Subscribe by email or SMS",
    },
  ].filter(Boolean) as any[];
  if (!actions.length && !s.whatsappLead) return null;
  return (
    <section className="lead-actions">
      <h3>Connect with me</h3>
      <div>
        {actions.map((x) => (
          <button
            key={x.key}
            onClick={() =>
              setForm({
                kind: x.key,
                title: x.title,
                item: x.title,
                dateTimeOptional: true,
              })
            }
          >
            <i className={`uil ${x.icon}`} />
            <span>
              <b>{x.title}</b>
              <small>{x.text}</small>
            </span>
            <i className="uil uil-angle-right" />
          </button>
        ))}
      </div>
      {s.whatsappLead && wa && (
        <a
          href={`https://wa.me/${wa}?text=${encodeURIComponent(`Hello ${p.name}, I found your mypag.ee profile and would like to connect.`)}`}
          target="_blank"
          onClick={() => track("whatsapp_click", "lead button")}
        >
          <i className="uil uil-whatsapp" /> Start on WhatsApp
        </a>
      )}
    </section>
  );
}
function TrackingScripts({ tracking }: { tracking: any }) {
  useEffect(() => {
    if (!tracking) return;
    if (tracking.googleAnalytics && !document.getElementById("mypagee-ga")) {
      const s = document.createElement("script");
      s.id = "mypagee-ga";
      s.async = true;
      s.src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(tracking.googleAnalytics)}`;
      document.head.appendChild(s);
      (window as any).dataLayer = (window as any).dataLayer || [];
      const gtag = (...args: any[]) => (window as any).dataLayer.push(args);
      gtag("js", new Date());
      gtag("config", tracking.googleAnalytics);
    }
    if (tracking.googleTagManager && !document.getElementById("mypagee-gtm")) {
      const s = document.createElement("script");
      s.id = "mypagee-gtm";
      s.async = true;
      s.src = `https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(tracking.googleTagManager)}`;
      document.head.appendChild(s);
    }
    if (tracking.facebookPixel && !(window as any).fbq) {
      const fbq: any = function (...args: any[]) {
        fbq.queue.push(args);
      };
      fbq.queue = [];
      (window as any).fbq = fbq;
      const s = document.createElement("script");
      s.async = true;
      s.src = "https://connect.facebook.net/en_US/fbevents.js";
      document.head.appendChild(s);
      fbq("init", tracking.facebookPixel);
      fbq("track", "PageView");
    }
  }, [
    tracking?.googleAnalytics,
    tracking?.googleTagManager,
    tracking?.facebookPixel,
  ]);
  return null;
}
function googleCalendarUrl(form: any) {
  const date = String(form.bookingData?.date || "").replaceAll("-", "");
  const time =
    String(form.bookingData?.time || "10:00").replace(":", "") + "00";
  const duration = Number(form.duration || 30);
  const start = new Date(
    `${form.bookingData?.date}T${form.bookingData?.time || "10:00"}:00`,
  );
  const end = new Date(start.getTime() + duration * 60000);
  const endDate = `${end.getFullYear()}${String(end.getMonth() + 1).padStart(2, "0")}${String(end.getDate()).padStart(2, "0")}T${String(end.getHours()).padStart(2, "0")}${String(end.getMinutes()).padStart(2, "0")}00`;
  return `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(form.item || form.title)}&dates=${date}T${time}/${endDate}&details=${encodeURIComponent(`Booked through mypag.ee${form.meetingLink ? `\n${form.meetingLink}` : ""}`)}`;
}
function isPro(p: any) {
  return p.plan === "pro" && (!p.proUntil || new Date(p.proUntil) > new Date());
}
function PublicAd({ p }: { p: any }) {
  const ad = p.adSettings || { mode: "manual" };
  useEffect(() => {
    if (!isPro(p) && ad.mode === "manual")
      fetch(`/api/public/${p.username}/ad`, { method: "POST" }).catch(() => {});
  }, [p.username, ad.mode]);
  useEffect(() => {
    if (isPro(p) || ad.mode !== "google" || !ad.googleClient || !ad.googleSlot)
      return;
    const id = "mypagee-adsense";
    if (!document.getElementById(id)) {
      const s = document.createElement("script");
      s.id = id;
      s.async = true;
      s.crossOrigin = "anonymous";
      s.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(ad.googleClient)}`;
      document.head.appendChild(s);
    }
    setTimeout(() => {
      try {
        (window as any).adsbygoogle = (window as any).adsbygoogle || [];
        (window as any).adsbygoogle.push({});
      } catch {}
    }, 200);
  }, [p.username, ad.mode, ad.googleClient, ad.googleSlot]);
  if (isPro(p) || ad.mode === "off") return null;
  if (ad.mode === "google" && ad.googleClient && ad.googleSlot)
    return (
      <div className="freead googlead">
        <small>ADVERTISEMENT</small>
        <ins
          className="adsbygoogle"
          style={{ display: "block" }}
          data-ad-client={ad.googleClient}
          data-ad-slot={ad.googleSlot}
          data-ad-format="auto"
          data-full-width-responsive="true"
        />
      </div>
    );
  return (
    <a
      className={`freead ${ad.manualImageUrl ? "manualad" : ""}`}
      href={`/api/public/${p.username}/ad`}
      target="_blank"
      rel="noopener sponsored"
    >
      {ad.manualImageUrl ? (
        <img src={ad.manualImageUrl} alt={ad.manualAlt || "Advertisement"} />
      ) : (
        <>
          <small>ADVERTISEMENT</small>
          <b>Build your page with mypag.ee</b>
          <span>Upgrade to Pro — ৳500/year or $5/year</span>
        </>
      )}
    </a>
  );
}
function vcardText(p: any) {
  const esc = (v: string) =>
    String(v || "")
      .replace(/\\/g, "\\\\")
      .replace(/\n/g, "\\n")
      .replace(/,/g, "\\,")
      .replace(/;/g, "\\;");
  const lines = [
    "BEGIN:VCARD",
    "VERSION:3.0",
    `FN:${esc(p.name)}`,
    `ORG:${esc(p.profileType === "business" ? p.name : "")}`,
    `TITLE:${esc(p.title)}`,
  ];
  (p.phones || []).forEach((x: any) =>
    lines.push(`TEL;TYPE=${esc(x.label).toUpperCase()}:${esc(x.value)}`),
  );
  (p.whatsapps || []).forEach((x: any) =>
    lines.push(`TEL;TYPE=CELL:${esc(x.value)}`),
  );
  (p.emails || []).forEach((x: any) =>
    lines.push(`EMAIL;TYPE=${esc(x.label).toUpperCase()}:${esc(x.value)}`),
  );
  (p.websites || []).forEach((x: any) => lines.push(`URL:${esc(x.value)}`));
  if (p.location) lines.push(`ADR:;;${esc(p.location)};;;;`);
  lines.push(`NOTE:${esc(p.bio)}`, "END:VCARD");
  return lines.join("\r\n");
}
function saveVCard(p: any) {
  const blob = new Blob([vcardText(p)], { type: "text/vcard;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download =
    (p.username || p.name || "contact").replace(/[^a-z0-9-]/gi, "-") + ".vcf";
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 500);
}
function VCardButton({
  p,
  track,
}: {
  p: any;
  track: (event: string, target?: string) => void;
}) {
  return (
    <button
      className="save-vcard-button"
      onClick={() => {
        track("vcard_save");
        saveVCard(p);
      }}
    >
      <i className="uil uil-user-plus" />
      <span>
        <b>Save V-Card</b>
        <small>Add this contact to your phone</small>
      </span>
      <i className="uil uil-import" />
    </button>
  );
}
function HomeActions({
  p,
  track,
}: {
  p: any;
  track: (event: string, target?: string) => void;
}) {
  const [sheet, setSheet] = useState<"" | "save" | "share">("");
  return (
    <>
      <div className="home-profile-actions">
        <button onClick={() => setSheet("save")}>
          <i className="uil uil-user-plus" /> Save V-Card
        </button>
        <button onClick={() => setSheet("share")}>
          <i className="uil uil-share-alt" /> Share profile
        </button>
      </div>
      {sheet && (
        <div className="action-sheet-backdrop" onClick={() => setSheet("")}>
          <section
            className="action-sheet"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="sheet-handle" />
            <ActionSheet
              p={p}
              type={sheet}
              close={() => setSheet("")}
              track={track}
            />
          </section>
        </div>
      )}
    </>
  );
}
function ActionSheet({
  p,
  type,
  close,
  track,
}: {
  p: any;
  type: "save" | "share";
  close: () => void;
  track: (event: string, target?: string) => void;
}) {
  const [copied, setCopied] = useState(false),
    [sent, setSent] = useState(""),
    url =
      typeof window !== "undefined"
        ? window.location.href
        : `https://mypag.ee/${p.username}`;
  const copy = async () => {
    await navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };
  const send = async (e: any) => {
    e.preventDefault();
    const el = e.currentTarget,
      data = Object.fromEntries(new FormData(el));
    const d = await fetch("/api/public/" + p.username, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ kind: "contact", data }),
    }).then((r) => r.json());
    if (d.reference) {
      setSent(d.reference);
      el.reset();
    }
  };
  if (type === "save")
    return (
      <>
        <div className="sheet-title save-title">
          <div>
            <h3>Save V-Card</h3>
            <p>{p.name}&apos;s contact details</p>
          </div>
          <button onClick={close} aria-label="Close">
            ×
          </button>
        </div>
        <div className="sheet-vcard">
          <div className="sheet-profile">
            <div>{p.name.slice(0, 2).toUpperCase()}</div>
            <span>
              <b>{p.name}</b>
              <small>{p.title}</small>
            </span>
          </div>
          {(p.phones || []).map((x: any, i: number) => (
            <a key={"sp" + i} href={"tel:" + x.value.replace(/[^0-9+]/g, "")}>
              <i className="uil uil-phone" />
              <span>
                <small>{x.label}</small>
                <b>{x.value}</b>
              </span>
            </a>
          ))}
          {(p.whatsapps || []).map((x: any, i: number) => (
            <a
              key={"sw" + i}
              href={"https://wa.me/" + x.value.replace(/[^0-9]/g, "")}
              target="_blank"
            >
              <i className="uil uil-whatsapp" />
              <span>
                <small>{x.label}</small>
                <b>{x.value}</b>
              </span>
            </a>
          ))}
          {(p.emails || []).map((x: any, i: number) => (
            <a key={"se" + i} href={"mailto:" + x.value}>
              <i className="uil uil-envelope" />
              <span>
                <small>{x.label}</small>
                <b>{x.value}</b>
              </span>
            </a>
          ))}
          {(p.websites || []).map((x: any, i: number) => (
            <a
              key={"su" + i}
              href={x.value.startsWith("http") ? x.value : "https://" + x.value}
              target="_blank"
            >
              <i className="uil uil-globe" />
              <span>
                <small>{x.label}</small>
                <b>{x.value}</b>
              </span>
            </a>
          ))}
        </div>
        <button
          className="download-vcard"
          onClick={() => {
            track("vcard_save");
            saveVCard(p);
          }}
        >
          <i className="uil uil-import" /> Save contact to phone
        </button>
        <form className="sheet-contact-form" onSubmit={send}>
          <h4>
            <i className="uil uil-message" /> Contact {p.name}
          </h4>
          {sent ? (
            <div className="sheet-sent">
              <i className="uil uil-check-circle" /> Message sent · {sent}
            </div>
          ) : (
            <>
              <input name="name" required placeholder="Your name" />
              <input name="phone" required placeholder="Phone / WhatsApp" />
              <input name="email" type="email" placeholder="Email (optional)" />
              <textarea
                name="message"
                required
                placeholder="Write your message"
              />
              <button>
                <i className="uil uil-message" /> Send message
              </button>
            </>
          )}
        </form>
        <button className="sheet-cancel" onClick={close}>
          Close
        </button>
      </>
    );
  return (
    <>
      <div className="sheet-title">
        <div>
          <h3>Share this profile</h3>
          <p>Choose where you want to share</p>
        </div>
        <button onClick={close} aria-label="Close">
          ×
        </button>
      </div>
      <div className="share-grid">
        <button onClick={copy}>
          <i className="uil uil-copy" />
          <span>{copied ? "Copied!" : "Copy link"}</span>
        </button>
        <a
          href={`https://wa.me/?text=${encodeURIComponent(p.name + " — " + url)}`}
          target="_blank"
        >
          <i className="uil uil-whatsapp" />
          <span>WhatsApp</span>
        </a>
        <a
          href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`}
          target="_blank"
        >
          <i className="uil uil-facebook-f" />
          <span>Facebook</span>
        </a>
        <a
          href={`mailto:?subject=${encodeURIComponent(p.name + " on mypag.ee")}&body=${encodeURIComponent(url)}`}
        >
          <i className="uil uil-envelope" />
          <span>Email</span>
        </a>
      </div>
      <button className="sheet-cancel" onClick={close}>
        Cancel
      </button>
    </>
  );
}
function ContactActions({
  p,
  track,
}: {
  p: any;
  track: (event: string, target?: string) => void;
}) {
  const [open, setOpen] = useState<
    "" | "phone" | "whatsapp" | "email" | "website"
  >("");
  const data = {
    phone: (p.phones || []).filter((x: any) => x.value),
    whatsapp: (p.whatsapps || []).filter((x: any) => x.value),
    email: (p.emails || []).filter((x: any) => x.value),
    website: (p.websites || []).filter((x: any) => x.value),
  };
  const href = (type: string, v: string) =>
    type === "phone"
      ? "tel:" + v.replace(/[^0-9+]/g, "")
      : type === "whatsapp"
        ? "https://wa.me/" + v.replace(/[^0-9]/g, "")
        : type === "email"
          ? "mailto:" + v
          : v.startsWith("http://") || v.startsWith("https://")
            ? v
            : "https://" + v;
  const action = (type: keyof typeof data) => {
    track(
      type === "phone"
        ? "phone_click"
        : type === "whatsapp"
          ? "whatsapp_click"
          : type === "email"
            ? "email_click"
            : "website_click",
      data[type][0]?.label || type,
    );
    if (data[type].length === 1)
      window.location.href = href(type, data[type][0].value);
    else if (data[type].length > 1) setOpen(type);
  };
  const item = (type: keyof typeof data, label: string, icon: string) =>
    data[type].length ? (
      <button onClick={() => action(type)} aria-label={label}>
        <i className={"uil " + icon} />
        <span>{label}</span>
      </button>
    ) : null;
  return (
    <>
      <div className={`quickcontacts design t${p.theme} ${p.profileType}`}>
        {item("phone", "Phone", "uil-phone")}
        {item("whatsapp", "WhatsApp", "uil-whatsapp")}
        {item("email", "Email", "uil-envelope")}
        {item("website", "Website", "uil-globe")}
      </div>
      {open && (
        <div
          className={`contactpopback design t${p.theme} ${p.profileType}`}
          onClick={() => setOpen("")}
        >
          <section className="contactpop" onClick={(e) => e.stopPropagation()}>
            <button className="popclose" onClick={() => setOpen("")}>
              ×
            </button>
            <i
              className={
                "uil " +
                (open === "phone"
                  ? "uil-phone"
                  : open === "whatsapp"
                    ? "uil-whatsapp"
                    : open === "email"
                      ? "uil-envelope"
                      : "uil-globe")
              }
            />
            <h3>
              {open === "phone"
                ? "Choose a phone number"
                : open === "whatsapp"
                  ? "Choose WhatsApp"
                  : open === "email"
                    ? "Choose an email"
                    : "Choose a website"}
            </h3>
            <div>
              {data[open].map((x: any, i: number) => (
                <a
                  key={i}
                  href={href(open, x.value)}
                  target={
                    open === "website" || open === "whatsapp"
                      ? "_blank"
                      : undefined
                  }
                  onClick={() =>
                    track(
                      open === "phone"
                        ? "phone_click"
                        : open === "whatsapp"
                          ? "whatsapp_click"
                          : open === "email"
                            ? "email_click"
                            : "website_click",
                      x.label,
                    )
                  }
                >
                  <span>{x.label}</span>
                  <b>{x.value}</b>
                  <i className="uil uil-arrow-up-right" />
                </a>
              ))}
            </div>
          </section>
        </div>
      )}
    </>
  );
}
