"use client";
import { useEffect, useState } from "react";
import AboutSection from "./about-section";
import CompanyBrand from "./company-brand";
import CompanyWorkspace, {
  CompanyData,
  CompanyLink,
} from "./company-workspace";
import ProfileBuilder, { BuilderSettings } from "./profile-builder";
import FieldManager from "./field-manager";
import EmailSignature, { SignatureSettings } from "./email-signature";
import LeadManager from "./lead-manager";
import AnalyticsDashboard from "./analytics-dashboard";
import {
  PROFILE_TYPES,
  COMPANY_PROFILE_TYPES,
  getProfileType,
  ProfileTypeKey,
} from "./profile-types";
type E = { label: string; value: string };
type I = {
  id: string;
  name: string;
  price: string;
  description: string;
  imageUrl?: string;
  itemType?: "physical" | "digital" | "course" | "service" | "booking";
  showPrice?: boolean;
  variants?: string;
  couponCode?: string;
  couponDiscount?: string;
  stock?: string;
  trackStock?: boolean;
  deliveryUrl?: string;
  checkoutMode?: "direct" | "whatsapp" | "both";
  bookingEnabled?: boolean;
  bookingPriceType?: "free" | "paid";
  duration?: string;
  dateTimeOptional?: boolean;
  availableSchedule?: string;
  meetingProvider?: "zoom" | "google-meet" | "custom";
  meetingLink?: string;
  bookingReminder?: string;
  consultationQuestions?: string;
};
type BookingSettings = {
  enabled: boolean;
  title: string;
  description: string;
  priceType: "free" | "paid";
  price: string;
  duration: string;
  dateTimeOptional: boolean;
  availableSchedule: string;
  meetingProvider: "zoom" | "google-meet" | "custom";
  meetingLink: string;
  reminder: string;
  consultationQuestions: string;
};
export type Link = {
  title: string;
  url: string;
  icon: string;
  thumbnailUrl?: string;
  featured?: boolean;
  startAt?: string;
  endAt?: string;
};
type Social = { platform: string; url: string; icon: string };
type AdSettings = {
  mode: "off" | "manual" | "google";
  manualImageUrl: string;
  manualLink: string;
  manualAlt: string;
  googleClient: string;
  googleSlot: string;
};
type P = {
  username: string;
  profileType: string;
  category: string;
  theme: number;
  name: string;
  title: string;
  bio: string;
  location: string;
  avatarUrl?: string;
  coverUrl?: string;
  plan?: "free" | "pro";
  proUntil?: string;
  adSettings?: AdSettings;
  company?: CompanyData;
  companyLink?: CompanyLink;
  builder?: BuilderSettings;
  emailSignature?: SignatureSettings;
  phones: E[];
  whatsapps: E[];
  emails: E[];
  websites: E[];
  links: Link[];
  socials: Social[];
  products: I[];
  services: I[];
  booking?: BookingSettings;
  leadSettings?: any;
  tracking?: any;
  menus: Record<string, boolean>;
};
const personal = [
    "Artist",
    "Actor",
    "Author",
    "Blogger",
    "Chef",
    "Coach",
    "Consultant",
    "Content Creator",
    "Designer",
    "Developer",
    "Doctor",
    "Educator",
    "Entrepreneur",
    "Fashion Creator",
    "Fitness Trainer",
    "Freelancer",
    "Gamer",
    "Influencer",
    "Journalist",
    "Lawyer",
    "Makeup Artist",
    "Mentor",
    "Musician",
    "Nutritionist",
    "Photographer",
    "Podcaster",
    "Public Speaker",
    "Real Estate Agent",
    "Researcher",
    "Singer",
    "Social Worker",
    "Student",
    "Teacher",
    "Therapist",
    "Travel Creator",
    "Video Creator",
    "Writer",
    "Architect",
    "Accountant",
    "Engineer",
    "Dentist",
    "Pharmacist",
    "Stylist",
    "Model",
    "Event Host",
    "Career Advisor",
    "Financial Advisor",
    "Digital Marketer",
    "Community Leader",
    "Nonprofit Professional",
  ],
  business = [
    "Advertising Agency",
    "Agriculture",
    "Architecture Firm",
    "Bakery",
    "Beauty Salon",
    "Bookstore",
    "Boutique",
    "Cafe",
    "Charity",
    "Clinic",
    "Coaching Center",
    "Construction",
    "Consulting Firm",
    "Digital Agency",
    "E-commerce Store",
    "Education",
    "Event Management",
    "Fashion Brand",
    "Financial Services",
    "Fitness Center",
    "Food Delivery",
    "Freelance Studio",
    "Furniture",
    "Gift Shop",
    "Graphic Design Studio",
    "Healthcare",
    "Home Business",
    "Hotel",
    "Interior Design",
    "IT Company",
    "Jewellery Brand",
    "Legal Firm",
    "Logistics",
    "Marketing Agency",
    "Media Company",
    "NGO",
    "Online Shop",
    "Photography Studio",
    "Printing Service",
    "Real Estate",
    "Restaurant",
    "Retail Store",
    "SaaS Company",
    "School",
    "Software Company",
    "Spa",
    "Tourism",
    "Training Center",
    "Travel Agency",
    "Wellness Center",
  ];
const themeNames = [
  "Signature",
  "Executive",
  "Bold Creator",
  "Brutalist",
  "Coastal Glass",
  "Neon Night",
  "Bubble Social",
  "Playful Cards",
  "Mono Studio",
  "Gradient Portal",
  "Local Pro",
  "Cosmic",
  "Terracotta",
  "Bento",
  "Botanical",
  "Tech Console",
  "Luxury Editorial",
  "Trust Blue",
  "Bold Flame",
  "Quiet Minimal",
];
const empty: P = {
  username: "username",
  profileType: "individual",
  category: "Personal Profile",
  theme: 1,
  name: "Your Name",
  title: "Professional title",
  bio: "Write a short introduction.",
  location: "Dhaka, Bangladesh",
  avatarUrl: "",
  coverUrl: "",
  plan: "free",
  proUntil: "",
  adSettings: {
    mode: "manual",
    manualImageUrl: "",
    manualLink: "https://mypag.ee",
    manualAlt: "Advertisement",
    googleClient: "",
    googleSlot: "",
  },
  phones: [],
  whatsapps: [],
  emails: [],
  websites: [],
  links: [],
  socials: [],
  products: [],
  services: [],
  booking: {
    enabled: false,
    title: "Book a private consultation",
    description:
      "Choose a suitable appointment time or send a request without selecting a time.",
    priceType: "free",
    price: "",
    duration: "30",
    dateTimeOptional: true,
    availableSchedule: "Sunday–Thursday, 10:00 AM–6:00 PM",
    meetingProvider: "google-meet",
    meetingLink: "",
    reminder: "24 hours before",
    consultationQuestions: "What would you like to discuss?",
  },
  leadSettings: {
    shareContact: true,
    inquiry: true,
    appointment: true,
    whatsappLead: true,
    subscriber: true,
    autoReplyEnabled: true,
    autoReplySubject: "Thanks for contacting me",
    autoReplyMessage:
      "Your information has been received. I will get back to you soon.",
  },
  tracking: { facebookPixel: "", googleAnalytics: "", googleTagManager: "" },
  menus: { home: true, vcard: true, shop: true, services: true, about: true },
};
const tabs = [
  "Profile",
  "Builder",
  "Company",
  "V-Card",
  "Links",
  "Social Media",
  "Products",
  "Services",
  "Booking",
  "Leads",
  "Analytics",
  "Inbox",
  "Email Signature",
  "Themes",
  "Ads",
  "Billing",
];
export default function CmsClient() {
  const [p, setP] = useState<P>(empty),
    [tab, setTab] = useState("Profile"),
    [subs, setSubs] = useState<any[]>([]),
    [msg, setMsg] = useState("");
  const load = () =>
    fetch("/api/cms")
      .then((r) => r.json())
      .then((d) => {
        setP(d.profile);
        setSubs(d.submissions);
      });
  useEffect(() => {
    load();
  }, []);
  const set = (x: Partial<P>) => setP((v) => ({ ...v, ...x }));
  const save = async () => {
    setMsg("Saving…");
    const d = await fetch("/api/cms", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ action: "save", profile: p }),
    }).then((r) => r.json());
    if (d.profile) setP(d.profile);
    setMsg(d.ok ? "Saved" : "Could not save");
    setTimeout(() => setMsg(""), 1800);
  };
  const addE = (k: "phones" | "whatsapps" | "emails" | "websites") =>
    set({
      [k]: [
        ...p[k],
        {
          label:
            k === "phones"
              ? "Mobile"
              : k === "whatsapps"
                ? "WhatsApp"
                : k === "emails"
                  ? "Work"
                  : "Website",
          value: "",
        },
      ],
    } as any);
  const editE = (
    k: "phones" | "whatsapps" | "emails" | "websites",
    i: number,
    q: keyof E,
    v: any,
  ) => {
    let a = [...p[k]];
    a[i] = { ...a[i], [q]: v };
    set({ [k]: a } as any);
  };
  const addI = (k: "products" | "services") =>
    set({
      [k]: [
        ...p[k],
        {
          id: crypto.randomUUID(),
          name: k === "products" ? "New product" : "New service",
          price: "",
          description: "",
          itemType: k === "products" ? "physical" : "booking",
          showPrice: true,
          variants: "",
          couponCode: "",
          couponDiscount: "",
          stock: "",
          trackStock: false,
          deliveryUrl: "",
          checkoutMode: "both",
          bookingEnabled: true,
          bookingPriceType: "free",
          duration: "30",
          dateTimeOptional: true,
          availableSchedule: "",
          meetingProvider: "google-meet",
          meetingLink: "",
          bookingReminder: "24 hours before",
          consultationQuestions: "What would you like to discuss?",
        },
      ],
    } as any);
  const editI = (k: "products" | "services", i: number, q: keyof I, v: any) => {
    let a = [...p[k]];
    a[i] = { ...a[i], [q]: v };
    set({ [k]: a } as any);
  };
  return (
    <main className="cms">
      <header className="bar">
        <b>
          mypag.<i>ee</i>
        </b>
        <div className="url">
          mypag.ee/<strong>{p.username || "username"}</strong>
        </div>
        <button onClick={save}>Save changes</button>
      </header>
      <div className="shell">
        <aside>
          <div className="mini">
            <span>{getProfileType(p.profileType).label[0]}</span>
            <div>
              <b>{p.name}</b>
              <small>{getProfileType(p.profileType).label} profile</small>
            </div>
          </div>
          {tabs
            .filter(
              (x) =>
                x !== "Company" ||
                COMPANY_PROFILE_TYPES.has(p.profileType as ProfileTypeKey),
            )
            .map((x) => (
              <button
                className={tab === x ? "active" : ""}
                key={x}
                onClick={() => setTab(x)}
              >
                {x}
              </button>
            ))}
        </aside>
        <section className="editor">
          <div className="heading">
            <div>
              <small>PROFILE CMS</small>
              <h1>{tab}</h1>
            </div>
            {msg && <span className="notice">{msg}</span>}
          </div>
          {tab === "Profile" && (
            <Card title="Profile photos">
              <div className="profilemedia">
                <CropUploader
                  label="Profile photo"
                  shape="avatar"
                  value={p.avatarUrl || ""}
                  onChange={(avatarUrl) => set({ avatarUrl })}
                />
                <CropUploader
                  label="Cover photo"
                  shape="cover"
                  value={p.coverUrl || ""}
                  onChange={(coverUrl) => set({ coverUrl })}
                />
              </div>
            </Card>
          )}
          {tab === "Profile" && (
            <>
              <Card title="Choose your profile type">
                <p className="helper">
                  Your dashboard and recommended fields will adapt to this
                  selection.
                </p>
                <div className="profiletypegrid">
                  {PROFILE_TYPES.map((x) => (
                    <button
                      key={x.key}
                      className={
                        p.profileType === x.key ||
                        (p.profileType === "personal" && x.key === "individual")
                          ? "on"
                          : ""
                      }
                      onClick={() =>
                        set({ profileType: x.key, category: x.categories[0] })
                      }
                    >
                      <i className={`uil ${x.icon}`} />
                      <span>
                        <b>{x.label}</b>
                        <small>{x.description}</small>
                      </span>
                      <i className="uil uil-check-circle" />
                    </button>
                  ))}
                </div>
                <F label="Profile address">
                  <div className="slug">
                    <span>mypag.ee/</span>
                    <input
                      value={p.username}
                      onChange={(e) =>
                        set({
                          username: e.target.value
                            .toLowerCase()
                            .replace(/[^a-z0-9-]/g, ""),
                        })
                      }
                    />
                  </div>
                </F>
                <F label="Type / category">
                  <select
                    value={
                      getProfileType(p.profileType).categories.includes(
                        p.category,
                      )
                        ? p.category
                        : "Other"
                    }
                    onChange={(e) =>
                      set({
                        category:
                          e.target.value === "Other" ? "" : e.target.value,
                      })
                    }
                  >
                    {getProfileType(p.profileType).categories.map((x) => (
                      <option key={x}>{x}</option>
                    ))}
                  </select>
                </F>
                {!getProfileType(p.profileType).categories.includes(
                  p.category,
                ) && (
                  <F label="Custom type">
                    <input
                      value={p.category}
                      onChange={(e) => set({ category: e.target.value })}
                      placeholder="Write your own category"
                    />
                  </F>
                )}
              </Card>
              <Card title="Public identity">
                <F
                  label={
                    COMPANY_PROFILE_TYPES.has(p.profileType as ProfileTypeKey)
                      ? "Business / organization name"
                      : "Full name"
                  }
                >
                  <input
                    value={p.name}
                    onChange={(e) => set({ name: e.target.value })}
                  />
                </F>
                <F label="Title / tagline">
                  <input
                    value={p.title}
                    onChange={(e) => set({ title: e.target.value })}
                  />
                </F>
                <F label="Bio">
                  <textarea
                    value={p.bio}
                    onChange={(e) => set({ bio: e.target.value })}
                  />
                </F>
                <F label="Location">
                  <input
                    value={p.location}
                    onChange={(e) => set({ location: e.target.value })}
                  />
                </F>
              </Card>
              <Card title="Optional public menus">
                <div className="toggles">
                  {Object.entries(p.menus).map(([k, v]) => (
                    <label key={k}>
                      <span>{k[0].toUpperCase() + k.slice(1)}</span>
                      <input
                        type="checkbox"
                        checked={v}
                        onChange={(e) =>
                          set({ menus: { ...p.menus, [k]: e.target.checked } })
                        }
                      />
                    </label>
                  ))}
                </div>
              </Card>
            </>
          )}
          {tab === "Company" &&
            COMPANY_PROFILE_TYPES.has(p.profileType as ProfileTypeKey) && (
              <CompanyWorkspace
                value={p.company}
                link={p.companyLink}
                businessName={p.name}
                username={p.username}
                requests={subs.filter(
                  (s) =>
                    s.kind === "company_link_request" && s.status === "new",
                )}
                onChange={(company) => set({ company })}
                onLinkChange={(companyLink) => set({ companyLink })}
                onSave={save}
                onRefresh={load}
              />
            )}
          {tab === "Builder" && (
            <ProfileBuilder
              value={p.builder}
              menus={p.menus}
              onChange={(builder, menus) => set({ builder, menus })}
              onSave={save}
            />
          )}
          {tab === "V-Card" && (
            <>
              {(["phones", "whatsapps", "emails", "websites"] as const).map(
                (k) => (
                  <Repeat
                    key={k}
                    title={
                      k === "phones"
                        ? "Phone numbers"
                        : k === "whatsapps"
                          ? "WhatsApp numbers"
                          : k === "emails"
                            ? "Email addresses"
                            : "Web addresses"
                    }
                    items={p[k]}
                    add={() => addE(k)}
                    edit={(i, q, v) => editE(k, i, q, v)}
                    remove={(i) =>
                      set({ [k]: p[k].filter((_, n) => n !== i) } as any)
                    }
                  />
                ),
              )}
            </>
          )}
          {tab === "Links" && (
            <FieldManager
              links={p.links}
              onChange={(links) => set({ links })}
              onSave={save}
            />
          )}
          {tab === "Social Media" && (
            <Card title="Social media profiles">
              <p className="helper">
                Add as many social profiles as needed. Select the correct
                IconScout icon for each platform.
              </p>
              {p.socials.map((x, i) => (
                <div className="line socialline" key={i}>
                  <IconPicker
                    value={x.icon}
                    onChange={(v) => {
                      let a = [...p.socials];
                      a[i] = { ...a[i], icon: v };
                      set({ socials: a });
                    }}
                  />
                  <input
                    value={x.platform}
                    onChange={(e) => {
                      let a = [...p.socials];
                      a[i] = { ...a[i], platform: e.target.value };
                      set({ socials: a });
                    }}
                    placeholder="Platform"
                  />
                  <input
                    value={x.url}
                    onChange={(e) => {
                      let a = [...p.socials];
                      a[i] = { ...a[i], url: e.target.value };
                      set({ socials: a });
                    }}
                    placeholder="Profile URL"
                  />
                  <button
                    onClick={() =>
                      set({ socials: p.socials.filter((_, n) => n !== i) })
                    }
                  >
                    ×
                  </button>
                </div>
              ))}
              <button
                className="add"
                onClick={() =>
                  set({
                    socials: [
                      ...p.socials,
                      {
                        platform: "New social",
                        url: "https://",
                        icon: "uil-share-alt",
                      },
                    ],
                  })
                }
              >
                ＋ Add social profile
              </button>
            </Card>
          )}
          {(tab === "Products" || tab === "Services") && (
            <ItemEditor
              kind={tab === "Products" ? "products" : "services"}
              items={tab === "Products" ? p.products : p.services}
              add={addI}
              edit={editI}
              set={set}
              save={save}
            />
          )}
          {tab === "Booking" && (
            <BookingManager
              value={p.booking}
              onChange={(booking) => set({ booking })}
              onSave={save}
            />
          )}
          {tab === "Leads" && (
            <LeadManager
              value={p.leadSettings}
              tracking={p.tracking}
              submissions={subs}
              onChange={(leadSettings) => set({ leadSettings })}
              onTrackingChange={(tracking) => set({ tracking })}
              onSave={save}
              onRefresh={load}
            />
          )}
          {tab === "Analytics" && <AnalyticsDashboard />}
          {tab === "Inbox" && (
            <Card title="Orders, bookings & contacts">
              {subs.length ? (
                subs.map((s) => (
                  <article className="inbox" key={s.id}>
                    <span>{s.kind}</span>
                    <b>{s.data?.name || "New request"}</b>
                    <p>
                      {s.data?.phone || s.data?.email || "Details received"}
                    </p>
                    <small>{new Date(s.created_at).toLocaleString()}</small>
                  </article>
                ))
              ) : (
                <div className="empty">No enquiries yet.</div>
              )}
            </Card>
          )}
          {tab === "Email Signature" && (
            <EmailSignature
              p={p}
              value={p.emailSignature}
              onChange={(emailSignature) => set({ emailSignature })}
              onSave={save}
            />
          )}
          {tab === "Themes" && (
            <div className="themes">
              {themeNames.map((name, i) => (
                <button
                  className={p.theme === i + 1 ? "chosen" : ""}
                  onClick={() => set({ theme: i + 1 })}
                  key={name}
                >
                  <span style={{ background: `hsl(${i * 29} 70% 52%)` }} />
                  <b>
                    {String(i + 1).padStart(2, "0")} · {name}
                  </b>
                  <small>Apply design</small>
                </button>
              ))}
            </div>
          )}
          {tab === "Ads" && <AdsManager p={p} set={set} save={save} />}
          {tab === "Billing" && <Billing p={p} />}
        </section>
        <section className="previewrail">
          <div className="previewsticky">
            <div className="previewlabel">
              <span>LIVE PREVIEW</span>
              <a href={`/${p.username || "username"}`} target="_blank">
                Open public profile ↗
              </a>
            </div>
            <Preview p={p} />
          </div>
        </section>
      </div>
    </main>
  );
}
function CropUploader({
  label,
  shape,
  value,
  onChange,
}: {
  label: string;
  shape: "avatar" | "cover";
  value: string;
  onChange: (url: string) => void;
}) {
  const [src, setSrc] = useState(""),
    [zoom, setZoom] = useState(1),
    [x, setX] = useState(0),
    [y, setY] = useState(0),
    [busy, setBusy] = useState(false);
  const choose = (file?: File) => {
    if (!file) return;
    setSrc(URL.createObjectURL(file));
    setZoom(1);
    setX(0);
    setY(0);
  };
  const crop = async () => {
    const img = new Image();
    img.src = src;
    await img.decode();
    const w = shape === "avatar" ? 600 : 1200,
      h = shape === "avatar" ? 600 : 500,
      canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext("2d")!,
      scale = Math.max(w / img.naturalWidth, h / img.naturalHeight) * zoom,
      dw = img.naturalWidth * scale,
      dh = img.naturalHeight * scale,
      maxX = Math.max(0, dw - w),
      maxY = Math.max(0, dh - h),
      dx = (w - dw) / 2 + (x / 100) * (maxX / 2),
      dy = (h - dh) / 2 + (y / 100) * (maxY / 2);
    ctx.drawImage(img, dx, dy, dw, dh);
    setBusy(true);
    const blob = await new Promise<Blob | null>((r) =>
      canvas.toBlob(r, "image/webp", 0.9),
    );
    if (blob) {
      const f = new FormData();
      f.append("file", blob, shape + ".webp");
      const d = await fetch("/api/upload", { method: "POST", body: f }).then(
        (r) => r.json(),
      );
      if (d.url) {
        onChange(d.url);
        setSrc("");
      } else alert(d.error || "Upload failed");
    }
    setBusy(false);
  };
  return (
    <div className={`mediauploader ${shape}`}>
      <span>{label}</span>
      <div className="mediathumb">
        {value ? (
          <img src={value} alt={label} />
        ) : (
          <i
            className={
              shape === "avatar" ? "uil uil-user-circle" : "uil uil-image"
            }
          />
        )}
      </div>
      <label className="mediachoose">
        <i className="uil uil-camera" /> {value ? "Change photo" : "Add photo"}
        <input
          type="file"
          accept="image/png,image/jpeg,image/webp"
          onChange={(e) => choose(e.target.files?.[0])}
        />
      </label>
      {value && (
        <button className="mediaremove" onClick={() => onChange("")}>
          Remove
        </button>
      )}
      {src && (
        <div className="cropback">
          <section className="cropbox">
            <h3>Crop {label}</h3>
            <div className={`cropstage ${shape}`}>
              <img
                src={src}
                alt="Crop preview"
                style={{
                  transform: `translate(${x / 2}%,${y / 2}%) scale(${zoom})`,
                }}
              />
            </div>
            <label>
              Zoom
              <input
                type="range"
                min="1"
                max="3"
                step=".05"
                value={zoom}
                onChange={(e) => setZoom(+e.target.value)}
              />
            </label>
            <label>
              Left / Right
              <input
                type="range"
                min="-100"
                max="100"
                value={x}
                onChange={(e) => setX(+e.target.value)}
              />
            </label>
            <label>
              Up / Down
              <input
                type="range"
                min="-100"
                max="100"
                value={y}
                onChange={(e) => setY(+e.target.value)}
              />
            </label>
            <div className="cropactions">
              <button onClick={() => setSrc("")}>Cancel</button>
              <button onClick={crop} disabled={busy}>
                {busy ? "Uploading…" : "Crop & use photo"}
              </button>
            </div>
          </section>
        </div>
      )}
    </div>
  );
}
function Billing({ p }: { p: P }) {
  const [msg, setMsg] = useState("");
  const pay = async (provider: "bkash" | "stripe") => {
    setMsg("Opening secure payment…");
    const d = await fetch("/api/billing", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ provider }),
    }).then((r) => r.json());
    if (d.url) window.location.href = d.url;
    else setMsg(d.error || "Payment is not available yet.");
  };
  const pro =
    p.plan === "pro" && (!p.proUntil || new Date(p.proUntil) > new Date());
  return (
    <>
      <Card title="Your plan">
        <div className={`planstatus ${pro ? "pro" : "free"}`}>
          <i className={pro ? "uil uil-award" : "uil uil-user"} />
          <div>
            <b>{pro ? "mypag.ee Pro" : "Free plan"}</b>
            <span>
              {pro
                ? `Ad-free${p.proUntil ? ` · Active until ${new Date(p.proUntil).toLocaleDateString()}` : ""}`
                : "Your public profile includes one ad banner."}
            </span>
          </div>
        </div>
      </Card>
      <div className="plans">
        <article>
          <small>CURRENT</small>
          <h2>Free</h2>
          <strong>৳0</strong>
          <p>Public profile, core tools and a 350×120 ad banner.</p>
        </article>
        <article className="proplan">
          <small>YEARLY</small>
          <h2>
            <i className="uil uil-award" /> Pro
          </h2>
          <strong>
            ৳500 <em>or $5 / year</em>
          </strong>
          <p>No ads, premium badge and all profile features.</p>
          <button onClick={() => pay("bkash")}>Pay ৳500 with bKash</button>
          <button onClick={() => pay("stripe")}>Pay $5 with card</button>
        </article>
      </div>
      {msg && <div className="billingmsg">{msg}</div>}
    </>
  );
}
function AdsManager({
  p,
  set,
  save,
}: {
  p: P;
  set: (x: Partial<P>) => void;
  save: () => void;
}) {
  const ad = p.adSettings || empty.adSettings!,
    [stats, setStats] = useState<any>({
      allTime: { view: 0, click: 0 },
      last30Days: { view: 0, click: 0 },
      daily: [],
    }),
    [uploading, setUploading] = useState(false);
  useEffect(() => {
    fetch("/api/ads")
      .then((r) => r.json())
      .then(setStats);
  }, []);
  const change = (x: Partial<AdSettings>) =>
    set({ adSettings: { ...ad, ...x } });
  const upload = async (file?: File) => {
    if (!file) return;
    setUploading(true);
    const f = new FormData();
    f.append("file", file);
    const d = await fetch("/api/upload", { method: "POST", body: f }).then(
      (r) => r.json(),
    );
    if (d.url) change({ manualImageUrl: d.url });
    else alert(d.error || "Upload failed");
    setUploading(false);
  };
  const views = stats.allTime?.view || 0,
    clicks = stats.allTime?.click || 0;
  return (
    <>
      <Card title="Ad banner control">
        <p className="helper">
          Choose one active ad source for free public profiles. Pro profiles
          remain ad-free.
        </p>
        <div className="admode">
          {(["off", "manual", "google"] as const).map((x) => (
            <button
              key={x}
              className={ad.mode === x ? "on" : ""}
              onClick={() => change({ mode: x })}
            >
              {x === "off"
                ? "Ads off"
                : x === "manual"
                  ? "Manual ad"
                  : "Google Ads"}
            </button>
          ))}
        </div>
        {ad.mode === "manual" && (
          <div className="adform">
            <F label="Banner image · recommended 350 × 120">
              <div className="adimage">
                {ad.manualImageUrl ? (
                  <img src={ad.manualImageUrl} alt="Ad preview" />
                ) : (
                  <span>
                    <i className="uil uil-image" /> No image selected
                  </span>
                )}
              </div>
              <label className="adupload">
                <i className="uil uil-upload" />{" "}
                {uploading ? "Uploading…" : "Upload image"}
                <input
                  type="file"
                  accept="image/png,image/jpeg,image/webp"
                  onChange={(e) => upload(e.target.files?.[0])}
                />
              </label>
            </F>
            <F label="Destination link">
              <input
                value={ad.manualLink}
                onChange={(e) => change({ manualLink: e.target.value })}
                placeholder="https://example.com"
              />
            </F>
            <F label="Image alt text">
              <input
                value={ad.manualAlt}
                onChange={(e) => change({ manualAlt: e.target.value })}
              />
            </F>
          </div>
        )}
        {ad.mode === "google" && (
          <div className="adform">
            <F label="Google publisher ID">
              <input
                value={ad.googleClient}
                onChange={(e) => change({ googleClient: e.target.value })}
                placeholder="ca-pub-1234567890"
              />
            </F>
            <F label="Google ad slot ID">
              <input
                value={ad.googleSlot}
                onChange={(e) => change({ googleSlot: e.target.value })}
                placeholder="1234567890"
              />
            </F>
            <p className="helper">
              Google click and revenue reporting remains in your AdSense
              dashboard.
            </p>
          </div>
        )}
        <button className="savead" onClick={save}>
          <i className="uil uil-save" /> Save ad settings
        </button>
      </Card>
      <Card title="Manual ad analytics">
        <div className="adstats">
          <div>
            <span>Total views</span>
            <b>{views.toLocaleString()}</b>
          </div>
          <div>
            <span>Total clicks</span>
            <b>{clicks.toLocaleString()}</b>
          </div>
          <div>
            <span>Click-through rate</span>
            <b>{views ? ((clicks / views) * 100).toFixed(2) : "0.00"}%</b>
          </div>
          <div>
            <span>Last 30 days</span>
            <b>
              {stats.last30Days?.view || 0} / {stats.last30Days?.click || 0}
            </b>
            <small>views / clicks</small>
          </div>
        </div>
      </Card>
    </>
  );
}
function Card({ title, children }: { title: string; children: any }) {
  return (
    <div className="card">
      <div className="cardhead">
        <h2>{title}</h2>
      </div>
      {children}
    </div>
  );
}
function F({ label, children }: { label: string; children: any }) {
  return (
    <label className="field">
      <span>{label}</span>
      {children}
    </label>
  );
}
function Repeat({
  title,
  items,
  add,
  edit,
  remove,
}: {
  title: string;
  items: E[];
  add: any;
  edit: any;
  remove: any;
}) {
  return (
    <Card title={title}>
      {items.map((x, i) => (
        <div className="line" key={i}>
          <input
            value={x.label}
            onChange={(e) => edit(i, "label", e.target.value)}
          />
          <input
            value={x.value}
            onChange={(e) => edit(i, "value", e.target.value)}
          />
          <button onClick={() => remove(i)}>×</button>
        </div>
      ))}
      {!items.length && <div className="empty">Nothing added yet.</div>}
      <button className="add" onClick={add}>
        ＋ Add another
      </button>
    </Card>
  );
}
function ItemEditor({
  kind,
  items,
  add,
  edit,
  set,
  save,
}: {
  kind: "products" | "services";
  items: I[];
  add: any;
  edit: any;
  set: any;
  save: any;
}) {
  const upload = async (file: File, i: number) => {
    const f = new FormData();
    f.append("file", file);
    const d = await fetch("/api/upload", { method: "POST", body: f }).then(
      (r) => r.json(),
    );
    if (d.url) edit(kind, i, "imageUrl", d.url);
    else alert(d.error || "Upload failed");
  };
  return (
    <Card
      title={kind === "products" ? "Products & orders" : "Services & bookings"}
    >
      {items.map((x, i) => (
        <div className="itemedit" key={x.id}>
          <div className="photoedit">
            {x.imageUrl ? (
              <img src={x.imageUrl} alt="" />
            ) : (
              <i
                className={
                  kind === "products"
                    ? "uil uil-shopping-bag"
                    : "uil uil-briefcase-alt"
                }
              />
            )}
            <label>
              <i className="uil uil-camera" />{" "}
              {x.imageUrl ? "Change photo" : "Add photo"}
              <input
                type="file"
                accept="image/png,image/jpeg,image/webp"
                onChange={(e) =>
                  e.target.files?.[0] && upload(e.target.files[0], i)
                }
              />
            </label>
          </div>
          <F label="Name">
            <input
              value={x.name}
              onChange={(e) => edit(kind, i, "name", e.target.value)}
            />
          </F>
          <F label={kind === "products" ? "Product type" : "Service type"}>
            <select
              value={
                x.itemType || (kind === "products" ? "physical" : "booking")
              }
              onChange={(e) => edit(kind, i, "itemType", e.target.value)}
            >
              {kind === "products" ? (
                <>
                  <option value="physical">Physical product</option>
                  <option value="digital">Digital product</option>
                  <option value="course">Course</option>
                </>
              ) : (
                <>
                  <option value="service">Service</option>
                  <option value="booking">Booking / consultation</option>
                </>
              )}
            </select>
          </F>
          <F label="Price (optional)">
            <input
              value={x.price}
              onChange={(e) => edit(kind, i, "price", e.target.value)}
            />
          </F>
          <label className="storetoggle">
            <input
              type="checkbox"
              checked={x.showPrice !== false}
              onChange={(e) => edit(kind, i, "showPrice", e.target.checked)}
            />
            <span>Show price publicly</span>
          </label>
          <F label="Description">
            <input
              value={x.description}
              onChange={(e) => edit(kind, i, "description", e.target.value)}
            />
          </F>
          <div className="storeoptions">
            <F label="Variants (comma separated)">
              <input
                value={x.variants || ""}
                onChange={(e) => edit(kind, i, "variants", e.target.value)}
                placeholder="Small, Medium, Large"
              />
            </F>
            <F label="Checkout method">
              <select
                value={x.checkoutMode || "both"}
                onChange={(e) => edit(kind, i, "checkoutMode", e.target.value)}
              >
                <option value="both">Direct + WhatsApp</option>
                <option value="direct">Direct checkout only</option>
                <option value="whatsapp">WhatsApp order only</option>
              </select>
            </F>
            <F label="Coupon code">
              <input
                value={x.couponCode || ""}
                onChange={(e) => edit(kind, i, "couponCode", e.target.value)}
                placeholder="SAVE10"
              />
            </F>
            <F label="Discount %">
              <input
                type="number"
                min="0"
                max="100"
                value={x.couponDiscount || ""}
                onChange={(e) =>
                  edit(kind, i, "couponDiscount", e.target.value)
                }
              />
            </F>
            {kind === "products" && (
              <>
                <label className="storetoggle">
                  <input
                    type="checkbox"
                    checked={!!x.trackStock}
                    onChange={(e) =>
                      edit(kind, i, "trackStock", e.target.checked)
                    }
                  />
                  <span>Track stock</span>
                </label>
                {x.trackStock && (
                  <F label="Available stock">
                    <input
                      type="number"
                      min="0"
                      value={x.stock || ""}
                      onChange={(e) => edit(kind, i, "stock", e.target.value)}
                    />
                  </F>
                )}
              </>
            )}
            {kind === "products" &&
              (x.itemType === "digital" || x.itemType === "course") && (
                <F label="Digital delivery file / access URL">
                  <input
                    value={x.deliveryUrl || ""}
                    onChange={(e) =>
                      edit(kind, i, "deliveryUrl", e.target.value)
                    }
                    placeholder="Secure file or course URL"
                  />
                </F>
              )}
            {kind === "services" && (
              <>
                <label className="storetoggle">
                  <input
                    type="checkbox"
                    checked={x.bookingEnabled !== false}
                    onChange={(e) =>
                      edit(kind, i, "bookingEnabled", e.target.checked)
                    }
                  />
                  <span>Enable service booking</span>
                </label>
                <F label="Booking type">
                  <select
                    value={x.bookingPriceType || "free"}
                    onChange={(e) =>
                      edit(kind, i, "bookingPriceType", e.target.value)
                    }
                  >
                    <option value="free">Free booking</option>
                    <option value="paid">Paid booking</option>
                  </select>
                </F>
                <F label="Duration (minutes)">
                  <input
                    type="number"
                    min="5"
                    value={x.duration || "30"}
                    onChange={(e) => edit(kind, i, "duration", e.target.value)}
                  />
                </F>
                <label className="storetoggle">
                  <input
                    type="checkbox"
                    checked={x.dateTimeOptional !== false}
                    onChange={(e) =>
                      edit(kind, i, "dateTimeOptional", e.target.checked)
                    }
                  />
                  <span>Date and time optional</span>
                </label>
                <F label="Available schedule">
                  <textarea
                    value={x.availableSchedule || ""}
                    onChange={(e) =>
                      edit(kind, i, "availableSchedule", e.target.value)
                    }
                    placeholder="Sunday–Thursday, 10 AM–6 PM"
                  />
                </F>
                <F label="Meeting platform">
                  <select
                    value={x.meetingProvider || "google-meet"}
                    onChange={(e) =>
                      edit(kind, i, "meetingProvider", e.target.value)
                    }
                  >
                    <option value="google-meet">Google Meet</option>
                    <option value="zoom">Zoom</option>
                    <option value="custom">Custom / in person</option>
                  </select>
                </F>
                <F label="Meeting link">
                  <input
                    value={x.meetingLink || ""}
                    onChange={(e) =>
                      edit(kind, i, "meetingLink", e.target.value)
                    }
                    placeholder="Added to booking confirmation"
                  />
                </F>
                <F label="Reminder">
                  <select
                    value={x.bookingReminder || "24 hours before"}
                    onChange={(e) =>
                      edit(kind, i, "bookingReminder", e.target.value)
                    }
                  >
                    <option>None</option>
                    <option>1 hour before</option>
                    <option>24 hours before</option>
                    <option>48 hours before</option>
                  </select>
                </F>
                <F label="Consultation questions">
                  <textarea
                    value={x.consultationQuestions || ""}
                    onChange={(e) =>
                      edit(kind, i, "consultationQuestions", e.target.value)
                    }
                    placeholder="One question per line"
                  />
                </F>
              </>
            )}
          </div>
          <div className="itemactions">
            <button className="saveitem" onClick={save}>
              <i className="uil uil-save" /> Save{" "}
              {kind === "products" ? "product" : "service"}
            </button>
            <button
              className="danger"
              onClick={() => set({ [kind]: items.filter((_, n) => n !== i) })}
            >
              Remove
            </button>
          </div>
        </div>
      ))}
      <div className="itemfooter">
        <button className="add" onClick={() => add(kind)}>
          ＋ Add {kind === "products" ? "product" : "service"}
        </button>
        {items.length > 0 && (
          <button className="saveall" onClick={save}>
            Save all
          </button>
        )}
      </div>
    </Card>
  );
}

function BookingManager({
  value,
  onChange,
  onSave,
}: {
  value?: BookingSettings;
  onChange: (value: BookingSettings) => void;
  onSave: () => void;
}) {
  const b: BookingSettings = value || empty.booking!;
  const setBooking = (patch: Partial<BookingSettings>) =>
    onChange({ ...b, ...patch });
  return (
    <Card title="Direct profile booking">
      <p className="helper">
        This is separate from service booking. Turn it on to show one general
        booking card directly on the profile home page.
      </p>
      <label className="booking-master">
        <span>
          <b>Direct booking</b>
          <small>
            {b.enabled
              ? "Visible on public profile"
              : "Hidden from public profile"}
          </small>
        </span>
        <input
          type="checkbox"
          checked={b.enabled}
          onChange={(e) => setBooking({ enabled: e.target.checked })}
        />
      </label>
      <div
        className={b.enabled ? "booking-settings" : "booking-settings disabled"}
      >
        <F label="Booking title">
          <input
            value={b.title}
            onChange={(e) => setBooking({ title: e.target.value })}
          />
        </F>
        <F label="Short description">
          <textarea
            value={b.description}
            onChange={(e) => setBooking({ description: e.target.value })}
          />
        </F>
        <div className="booking-grid">
          <F label="Free or paid">
            <select
              value={b.priceType}
              onChange={(e) => setBooking({ priceType: e.target.value as any })}
            >
              <option value="free">Free booking</option>
              <option value="paid">Paid booking</option>
            </select>
          </F>
          {b.priceType === "paid" && (
            <F label="Booking price">
              <input
                value={b.price}
                onChange={(e) => setBooking({ price: e.target.value })}
                placeholder="500"
              />
            </F>
          )}
          <F label="Duration (minutes)">
            <input
              type="number"
              min="5"
              value={b.duration}
              onChange={(e) => setBooking({ duration: e.target.value })}
            />
          </F>
          <F label="Meeting platform">
            <select
              value={b.meetingProvider}
              onChange={(e) =>
                setBooking({ meetingProvider: e.target.value as any })
              }
            >
              <option value="google-meet">Google Meet</option>
              <option value="zoom">Zoom</option>
              <option value="custom">Custom / in person</option>
            </select>
          </F>
        </div>
        <label className="storetoggle">
          <input
            type="checkbox"
            checked={b.dateTimeOptional}
            onChange={(e) => setBooking({ dateTimeOptional: e.target.checked })}
          />
          <span>Date and time optional</span>
        </label>
        <F label="Available schedule">
          <textarea
            value={b.availableSchedule}
            onChange={(e) => setBooking({ availableSchedule: e.target.value })}
            placeholder="Sunday–Thursday, 10:00 AM–6:00 PM"
          />
        </F>
        <F label="Zoom / Google Meet / location link">
          <input
            value={b.meetingLink}
            onChange={(e) => setBooking({ meetingLink: e.target.value })}
            placeholder="Shared after booking confirmation"
          />
        </F>
        <F label="Booking reminder">
          <select
            value={b.reminder}
            onChange={(e) => setBooking({ reminder: e.target.value })}
          >
            <option>None</option>
            <option>1 hour before</option>
            <option>24 hours before</option>
            <option>48 hours before</option>
          </select>
        </F>
        <F label="Consultation form questions">
          <textarea
            value={b.consultationQuestions}
            onChange={(e) =>
              setBooking({ consultationQuestions: e.target.value })
            }
            placeholder="One question per line"
          />
        </F>
      </div>
      <button className="saveall" onClick={onSave}>
        Save booking settings
      </button>
    </Card>
  );
}
const icons = [
  "uil-link",
  "uil-globe",
  "uil-shopping-bag",
  "uil-store",
  "uil-briefcase-alt",
  "uil-calendar-alt",
  "uil-phone",
  "uil-envelope",
  "uil-whatsapp",
  "uil-facebook-f",
  "uil-instagram",
  "uil-linkedin",
  "uil-youtube",
  "uil-twitter",
  "uil-tiktok",
  "uil-telegram",
  "uil-location-point",
  "uil-book-open",
  "uil-graduation-cap",
  "uil-camera",
  "uil-heart",
  "uil-star",
  "uil-play-circle",
  "uil-file-download",
  "uil-comment-alt",
  "uil-share-alt",
  "uil-user",
  "uil-users-alt",
  "uil-music",
  "uil-rss",
];
function IconPicker({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <label className="iconpick">
      <i className={"uil " + value} />
      <select value={value} onChange={(e) => onChange(e.target.value)}>
        {icons.map((x) => (
          <option key={x} value={x}>
            {x.replace("uil-", "").replaceAll("-", " ")}
          </option>
        ))}
      </select>
    </label>
  );
}
function PreviewContacts({ p }: { p: P }) {
  const [open, setOpen] = useState<
    "" | "phone" | "whatsapp" | "email" | "website"
  >("");
  const data = {
    phone: p.phones || [],
    whatsapp: p.whatsapps || [],
    email: p.emails || [],
    website: p.websites || [],
  };
  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) => {
    if (data[type].length === 1)
      window.location.href = href(type, data[type][0].value);
    else setOpen(type);
  };
  return (
    <>
      <div className="quickcontacts">
        {data.phone.length > 0 && (
          <button onClick={() => action("phone")}>
            <i className="uil uil-phone" />
            <span>Call</span>
          </button>
        )}
        {data.whatsapp.length > 0 && (
          <button onClick={() => action("whatsapp")}>
            <i className="uil uil-whatsapp" />
            <span>WhatsApp</span>
          </button>
        )}
        {data.email.length > 0 && (
          <button onClick={() => action("email")}>
            <i className="uil uil-envelope" />
            <span>Email</span>
          </button>
        )}
        {data.website.length > 0 && (
          <button onClick={() => action("website")}>
            <i className="uil uil-globe" />
            <span>Website</span>
          </button>
        )}
      </div>
      {open && (
        <div className="contactpopback" 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>Choose {open}</h3>
            <div>
              {data[open].map((x, i) => (
                <a key={i} href={href(open, x.value)}>
                  <span>{x.label}</span>
                  <b>{x.value}</b>
                  <i className="uil uil-arrow-up-right" />
                </a>
              ))}
            </div>
          </section>
        </div>
      )}
    </>
  );
}
function Preview({ p }: { p: P }) {
  const [view, setView] = useState("home"),
    builder = p.builder || {
      menuOrder: ["home", "vcard", "shop", "services", "about"],
      accentColor: "",
      font: "modern",
      buttonStyle: "rounded",
    },
    now = Date.now(),
    links = p.links.filter(
      (x) =>
        (!x.startAt || new Date(x.startAt).getTime() <= now) &&
        (!x.endAt || new Date(x.endAt).getTime() >= now),
    ),
    order = builder.menuOrder?.length
      ? builder.menuOrder
      : Object.keys(p.menus);
  return (
    <div
      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}</h2>
      <b>{p.title}</b>
      <p>{p.bio}</p>
      <small>
        {p.category} · {p.location}
      </small>
      <CompanyBrand p={p} />
      <PreviewContacts p={p} />
      <div className="socialicons">
        {(p.socials || []).map((x, i) => (
          <a href={x.url} key={i} title={x.platform}>
            <i className={"uil " + x.icon} />
          </a>
        ))}
      </div>
      <nav className="previewnav">
        {order
          .filter((k) => p.menus[k])
          .map((k) => (
            <button
              key={k}
              className={view === k ? "on" : ""}
              onClick={() => setView(k)}
            >
              {k}
            </button>
          ))}
      </nav>
      {view === "home" && (
        <>
          <div className="plinks">
            {links.map((x, i) => (
              <a
                className={x.featured ? "featuredlink" : ""}
                href={x.url}
                key={i}
              >
                {x.thumbnailUrl ? (
                  <img src={x.thumbnailUrl} alt="" />
                ) : (
                  <i className={"uil " + (x.icon || "uil-link")} />
                )}
                <b>{x.title}</b>
                <span>↗</span>
              </a>
            ))}
          </div>
          <div className="home-profile-actions">
            <button>
              <i className="uil uil-user-plus" /> Save V-Card
            </button>
            <button>
              <i className="uil uil-share-alt" /> Share profile
            </button>
          </div>
          {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>
              </div>
              <button>Book now</button>
            </div>
          )}
        </>
      )}
      {view === "vcard" && (
        <div className="contacts">
          {p.phones.map((x, i) => (
            <span key={"p" + i}>
              <i className="uil uil-phone" /> {x.label}: {x.value}
            </span>
          ))}
          {(p.whatsapps || []).map((x, i) => (
            <span key={"wa" + i}>
              <i className="uil uil-whatsapp" /> {x.label}: {x.value}
            </span>
          ))}
          {p.emails.map((x, i) => (
            <span key={"e" + i}>
              <i className="uil uil-envelope" /> {x.label}: {x.value}
            </span>
          ))}
          {p.websites.map((x, i) => (
            <span key={"w" + i}>
              <i className="uil uil-globe" /> {x.label}: {x.value}
            </span>
          ))}
        </div>
      )}
      {view === "shop" && (
        <div className="previewitems">
          {p.products.map((x) => (
            <article
              key={x.id}
              className={x.trackStock && Number(x.stock) <= 0 ? "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">
                  {Number(x.stock) <= 0
                    ? "Out of stock"
                    : `${x.stock} available`}
                </small>
              )}
              <button>
                <i className="uil uil-shopping-bag" /> Order now
              </button>
            </article>
          ))}
        </div>
      )}
      {view === "services" && (
        <div className="previewservices">
          {p.services.map((x) => (
            <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>Book</button>}
            </article>
          ))}
        </div>
      )}
      {view === "about" && <AboutSection p={p} />}
      <footer>Made with mypag.ee/{p.username || "username"}</footer>
    </div>
  );
}
