// components/BrandingCard.jsx
import React from 'react';
import { Palette, LayoutGrid, List, Search, ChevronLeft, ChevronRight, ZoomIn, Download, Image as ImageIcon, X } from 'lucide-react';

export const BRAND_DEFAULTS = {
    accent: '#6366f1',
    toolbar: 'dark',
    corners: 'round',
    font: 'system',
    logo: 0,
    logo_url: '',
    logo_toolbar: true,
    logo_loader: true,
};

const SWATCHES = ['#6366f1', '#2563eb', '#0d9488', '#16a34a', '#ea580c', '#dc2626', '#db2777', '#0f172a'];

// Mirrors BARS in src/frontend/brand.ts and the viewer's default dark bar.
const BAR = {
    dark: { bg: 'rgba(17, 24, 39, 0.82)', fg: '#f8fafc', muted: 'rgba(226, 232, 240, 0.72)', border: 'rgba(255, 255, 255, 0.08)' },
    light: { bg: 'rgba(255, 255, 255, 0.92)', fg: '#0f172a', muted: '#64748b', border: 'rgba(15, 23, 42, 0.1)' },
    glass: { bg: 'rgba(15, 23, 42, 0.32)', fg: '#ffffff', muted: 'rgba(255, 255, 255, 0.75)', border: 'rgba(255, 255, 255, 0.28)' },
};
const RADIUS = { round: [16, 10], soft: [10, 6], square: [3, 2] };

const Segmented = ({ value, options, onChange }) => (
    <div className="inline-flex rounded-lg bg-slate-100 p-0.5">
        {options.map(([v, label]) => (
            <button
                key={v}
                type="button"
                onClick={() => onChange(v)}
                className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${value === v ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-800'}`}
            >
                {label}
            </button>
        ))}
    </div>
);

const Preview = ({ brand }) => {
    const bar = BAR[brand.toolbar] || BAR.dark;
    const [outer, inner] = RADIUS[brand.corners] || RADIUS.round;
    const font = brand.font === 'site' ? 'inherit' : undefined;
    const btn = (Icon, active) => (
        <span
            className="flex size-7 items-center justify-center"
            style={{ borderRadius: inner, background: active ? brand.accent : 'transparent', color: active ? '#fff' : bar.fg }}
        >
            <Icon className="size-3.5" />
        </span>
    );
    return (
        <div
            className="relative flex h-[220px] items-end justify-center overflow-hidden rounded-xl p-4"
            style={{ background: 'linear-gradient(135deg, #e2e8f0, #cbd5e1 45%, #94a3b8)' }}
        >
            {/* mock page */}
            <div className="absolute left-1/2 top-4 h-[150px] w-[112px] -translate-x-1/2 rounded-sm bg-white p-2.5 shadow-lg">
                <div className="h-2 w-3/5 rounded" style={{ background: brand.accent }} />
                {[0.9, 0.75, 0.85, 0.6, 0.8, 0.7].map((w, i) => (
                    <div key={i} className="mt-1.5 h-1 rounded bg-slate-200" style={{ width: `${w * 100}%` }} />
                ))}
                <div className="mt-2 h-8 rounded-sm" style={{ background: `${brand.accent}22` }} />
            </div>
            <div
                className="relative flex items-center gap-0.5 p-1 shadow-xl"
                style={{ background: bar.bg, color: bar.fg, border: `1px solid ${bar.border}`, borderRadius: outer, backdropFilter: 'blur(14px)', fontFamily: font }}
            >
                {brand.logo_url && brand.logo_toolbar && (
                    <span className="mx-1 flex items-center pr-2" style={{ borderRight: `1px solid ${bar.border}` }}>
                        <img src={brand.logo_url} alt="" className="max-h-4 max-w-[60px] object-contain" />
                    </span>
                )}
                {btn(LayoutGrid, true)}
                {btn(List)}
                {btn(Search)}
                <span className="mx-1 h-4 w-px" style={{ background: bar.border }} />
                {btn(ChevronLeft)}
                <span className="px-1.5 text-[11px] font-semibold tabular-nums whitespace-nowrap" style={{ color: bar.fg }}>
                    3 <span style={{ color: bar.muted }}>/ 24</span>
                </span>
                {btn(ChevronRight)}
                <span className="mx-1 h-4 w-px" style={{ background: bar.border }} />
                {btn(ZoomIn)}
                {btn(Download)}
            </div>
        </div>
    );
};

const BrandingCard = ({ Card, Switch, brand, setBrand }) => {
    const b = { ...BRAND_DEFAULTS, ...brand };

    const pickLogo = () => {
        const frame = window.wp.media({
            title: 'Viewer logo',
            button: { text: 'Use this logo' },
            library: { type: 'image' },
            multiple: false,
        });
        frame.on('select', () => {
            const a = frame.state().get('selection').first().toJSON();
            setBrand({ logo: a.id, logo_url: a.sizes?.medium?.url || a.url });
        });
        frame.open();
    };

    return (
        <Card icon={Palette} title="Branding" description="Colours, shape and logo for every viewer on your site.">
            <div className="grid md:grid-cols-[1fr_280px] gap-8">
                <div className="space-y-5">
                    <div>
                        <span className="block text-sm font-medium text-slate-800 mb-2">Accent colour</span>
                        <div className="flex flex-wrap items-center gap-1.5">
                            {SWATCHES.map((c) => (
                                <button
                                    key={c}
                                    type="button"
                                    title={c}
                                    onClick={() => setBrand({ accent: c })}
                                    style={{ backgroundColor: c }}
                                    className={`size-7 rounded-full border border-black/10 ${b.accent.toLowerCase() === c ? 'ring-2 ring-offset-2 ring-slate-400' : ''}`}
                                />
                            ))}
                            <label className="relative ml-1 inline-flex items-center gap-2 text-xs text-slate-600 cursor-pointer">
                                <input type="color" value={b.accent} onChange={(e) => setBrand({ accent: e.target.value })} className="h-7 w-10 cursor-pointer rounded-md border border-slate-200 bg-white" style={{ padding: 2 }} />
                                <span className="font-mono">{b.accent}</span>
                            </label>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-x-6 gap-y-4">
                        <div>
                            <span className="block text-xs font-medium text-slate-600 mb-1.5">Toolbar</span>
                            <Segmented value={b.toolbar} onChange={(toolbar) => setBrand({ toolbar })} options={[['dark', 'Dark'], ['light', 'Light'], ['glass', 'Glass']]} />
                        </div>
                        <div>
                            <span className="block text-xs font-medium text-slate-600 mb-1.5">Corners</span>
                            <Segmented value={b.corners} onChange={(corners) => setBrand({ corners })} options={[['round', 'Round'], ['soft', 'Soft'], ['square', 'Square']]} />
                        </div>
                        <div>
                            <span className="block text-xs font-medium text-slate-600 mb-1.5">Font</span>
                            <Segmented value={b.font} onChange={(font) => setBrand({ font })} options={[['system', 'System'], ['site', 'Your theme']]} />
                        </div>
                    </div>
                    <div>
                        <span className="block text-sm font-medium text-slate-800 mb-2">Logo</span>
                        {b.logo ? (
                            <div className="flex items-center gap-3">
                                <span className="flex h-12 w-24 items-center justify-center rounded-lg border border-slate-200 bg-slate-50 p-1.5">
                                    {b.logo_url ? <img src={b.logo_url} alt="" className="max-h-full max-w-full object-contain" /> : <ImageIcon className="size-5 text-slate-400" />}
                                </span>
                                <button type="button" onClick={pickLogo} className="text-xs font-semibold text-indigo-600 hover:text-indigo-800">Change</button>
                                <button type="button" onClick={() => setBrand({ logo: 0, logo_url: '' })} className="inline-flex items-center gap-1 text-xs font-semibold text-slate-500 hover:text-red-600">
                                    <X className="size-3.5" /> Remove
                                </button>
                            </div>
                        ) : (
                            <button type="button" onClick={pickLogo} className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:border-indigo-300 hover:text-indigo-700">
                                <ImageIcon className="size-3.5" /> Choose logo
                            </button>
                        )}
                        {!!b.logo && (
                            <div className="mt-2 divide-y divide-slate-100">
                                <Switch label="In the toolbar" hint="Hidden on narrow screens." checked={!!b.logo_toolbar} onChange={(logo_toolbar) => setBrand({ logo_toolbar })} />
                                <Switch label="On the loading screen" checked={!!b.logo_loader} onChange={(logo_loader) => setBrand({ logo_loader })} />
                            </div>
                        )}
                    </div>
                </div>
                <div className="flex flex-col items-center gap-2">
                    <Preview brand={b} />
                    <span className="text-[11px] text-slate-500">Preview</span>
                </div>
            </div>
        </Card>
    );
};

export default BrandingCard;
