// ██████  ██  ██████  ██ ████████  █████  ██          ███████  ██████  ██    ██ ██      
// ██   ██ ██ ██       ██    ██    ██   ██ ██          ██      ██    ██ ██    ██ ██      
// ██   ██ ██ ██   ███ ██    ██    ███████ ██          ███████ ██    ██ ██    ██ ██      
// ██   ██ ██ ██    ██ ██    ██    ██   ██ ██               ██ ██    ██ ██    ██ ██      
// ██████  ██  ██████  ██    ██    ██   ██ ███████     ███████  ██████   ██████  ███████
//
// SPDX-License-Identifier: MIT
// Copyright Han, 2023

pragma solidity ^0.8.21;

contract DigitalSoul {
    event ArtpieceCreated(address indexed creator);
    event ArtpieceTransferred(address indexed oldOwner, address indexed newOwner);
    event BidAccepted(uint256 value, address indexed fromAddress, address indexed toAddress);
    event BidPlaced(uint256 value, address indexed fromAddress);
    event BidWithdrawn(uint256 value, address indexed fromAddress);
    event ListedForSale(uint256 value, address indexed fromAddress, address indexed toAddress);
    event SaleCanceled(uint256 value, address indexed fromAddress, address indexed toAddress);
    event SaleCompleted(uint256 value, address indexed fromAddress, address indexed toAddress);

    error FundsTransfer();
    error InsufficientFunds();
    error ListedForSaleToSpecificAddress();
    error NoBid();
    error NotForSale();
    error NotOwner();
    error NotRoyaltyRecipient();
    error NotYourBid();
    error NullAddress();
    error RoyaltyTooHigh();

    string public constant MANIFEST = (
        'We leave traces of our actions, thoughts and emotions, creating a digital reflection of our true selves.' '\n'
    );

    string public constant CORE = (
        'const DIRECTIVES=["#ifdef GL_ES","precision highp float;","#endif","#define AA 2","#define R(a)mat2(cos(a),sin(a),-sin(a),cos(a))"].map((e=>`${e}${String.fromCharCode(10)}`)).join("");let frag_piece=`${DIRECTIVES}uniform vec2 u_resolution,u_mouse;uniform float u_time;float v,x;vec3 t(vec3 v){v=vec3(dot(v,vec3(127.1,311.7,74.7)),dot(v,vec3(269.5,183.3,246.1)),dot(v,vec3(113.5,271.9,124.6)));return-1.+2.*fract(sin(v)*43758.5453123);}vec3 n(vec3 v){return clamp(v*(2.51*v+.03)/(v*(2.43*v+.59)+.14),0.,1.);}float f(vec3 v){v=fract(v*.3183099+.1);v*=17.;return fract(v.x*v.y*v.z*(v.x+v.y+v.z));}float m(vec3 v){vec3 x=floor(v),y=fract(v);y=y*y*(3.-2.*y);return mix(mix(mix(f(x+vec3(0)),f(x+vec3(1,0,0)),y.x),mix(f(x+vec3(0,1,0)),f(x+vec3(1,1,0)),y.x),y.y),mix(mix(f(x+vec3(0,0,1)),f(x+vec3(1,0,1)),y.x),mix(f(x+vec3(0,1,1)),f(x+vec3(1)),y.x),y.y),y.z);}float f(vec3 v,float x){vec3 f=v;float y=step(f.x,0.)*2.-1.,r;f.x=abs(f.x)-.8;f.x-=(sin(x)*.5+.5)*.125;r=length(f)-.4;f.zy*=R(x*2.);f.z-=.532*y;return min(r,length(f)-.132);}vec2 s(vec3 v){float y=0.,r=1e2,a=x,i=r,m;vec3 u=v;u=v.xyz;u.xy*=R(a);i=f(u,a);r=min(r,i);u=v.zxy;u.xy*=R(a);i=f(u,a);r=min(r,i);u=v.yzx;u.xy*=R(a);i=f(u,a);r=min(r,i);m=length(v)-.4;if(r>m)r=m,y=1.;i=max(-r,length(vec2(length(v.xz)-.4,v.y))-.025);return vec2(r,y);}vec3 p(vec3 v){vec2 y=vec2(.002,0);float f=s(v).x;return normalize(vec3(f-s(v-y.xyy).x,f-s(v-y.yxy).x,f-s(v-y.yyx).x));}vec2 m(vec3 v,vec3 y){float x=0.;vec2 f;for(int r=0;r<64;r++){vec3 a=v+y*x;f=s(a);x+=f.x;if(x>20.||abs(f.x)<.005)break;}x=min(x,20.);return vec2(x,f.y);}float n(vec3 v,vec3 y){float x=0.,f=1.;for(int r=0;r<4;r++){float u=.01+.033*float(r)/4.,a=s(v+u*y).x;x+=(u-a)*f;f*=.95;if(x>.35)break;}return clamp(1.-3.*x,0.,1.);}float p(vec3 v,vec3 y){float x=1.,a=(.8-v.y)/y.y,r,f;if(a>0.)x=min(x,a);r=1.;f=.01;for(int i=0;i<8;i++){float u=s(v+y*f).x,A=clamp(.5*u/f,0.,1.);r=min(r,A*A*(3.-2.*A));f+=clamp(u,.002,.05);if(r<.005||f>x)break;}return clamp(r,0.,1.);}vec4 s(vec3 v,vec3 r){vec3 y=p(v),f=vec3(0,-10,0),i;f.x+=sin(x*2.)*10.;f.z+=cos(-x)*10.;f=normalize(v-f);float a=clamp(dot(f,y),0.,1.),u=clamp(1.+dot(r,y),0.,1.),m=clamp(dot(reflect(-f,y),-r),0.,1.),A=n(v,y),z;i=mix(vec3(.6745),vec3(2),a);i+=vec3(1)*pow(u,7.);i+=vec3(1)*pow(m,2.)*.75;i*=mix(.1,1.,A);z=p(v,v+vec3(0));i=mix(i*vec3(.6941),i,z);return vec4(i,u);}vec2 t(vec3 v,vec3 y){float x=dot(v,y),r=x*x-dot(v,v)+2.25;if(r<0.)return vec2(-1);r=sqrt(r);return vec2(-x-r,-x+r);}vec4 f(vec2 x,vec2 y,float a){vec2 f=(x-.5*y)/min(y.y,y.x),r,i;vec3 u=vec3(0,10,-10),A,z,d,l,b,k;u.yz*=R(u_mouse.y/y.y*(2.*acos(-1.))*2.);u.xz*=R(u_mouse.x/y.x*(2.*acos(-1.))*2.);A=normalize(vec3(0)-u);z=normalize(vec3(A.z,0,-A.x));d=normalize(f.x*z+f.y*cross(A,z)+A/.37);r=t(u,d);i=r.x>0.?m(u,d):vec2(-1,0);l=u+d*i.x;b=vec3(0);if(i.x>.005)b=s(l,d).xyz;float c=smoothstep(3.,5.,length(l)),g=m(vec3(f*0.,v*16.));g=pow(g,1.33);k=mix(vec3(.5875),vec3(1)*3.,g);b=mix(b,k,c);b=n(b);return vec4(b,c);}float r(float v){vec3 f=fract(vec3(v)*443.8975);f+=dot(f,f.yzx+3.19);return fract((f.x+f.y)*f.z);}float c(float v){float x=floor(v);return mix(r(x),r(x+2.),smoothstep(0.,1.,fract(v)));}vec4 c(vec2 r,vec2 y){vec4 i=vec4(0,0,0,1);float a=.5+.5*sin(r.x*147.)*sin(r.y*131.),u=c(u_time*3.),A;u=pow(u,2.);u=smoothstep(.5,1.,u);A=.25*u;for(int z=0;z<AA;z++)for(int m=0;m<AA;m++){float s=u_time-.1*(float(z*AA+m)+a)/float(AA*AA);vec2 b=r+vec2(m,z)/float(AA);v=(s-A)/2.;x=2.*acos(-1.)*v;i.x+=f(b,y,-1.).x;v=s/2.;x=2.*acos(-1.)*v;i.y+=f(b,y,0.).y;v=(s+A)/2.;x=2.*acos(-1.)*v;i.z+=f(b,y,1.).z;}i/=float(AA*AA);return i;}void main(){vec2 v=gl_FragCoord.xy;gl_FragColor=vec4(c(v,u_resolution).xyz+fract(555.*sin(777.*t(v.xyy)))/256.,1);}`,vert_shader="attribute vec2 p;void main(){gl_Position=vec4(p,1.0,1.0);}",w=window,d=document,device_ratio=window.devicePixelRatio,pixel=new Uint8Array(4),is_mobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),canvas=d.querySelector("canvas");if(document.body.style.touchAction="none",document.body.style.userSelect="none",!canvas){canvas=d.createElement("canvas"),canvas.style.display="block";var body=d.body;body||(body=d.createElement("body")),body.appendChild(canvas),d.documentElement.appendChild(body)}let webglOptions={};is_mobile||(webglOptions={powerPreference:"high-performance"});let webgl=canvas.getContext("webgl",webglOptions);webgl.program=null,webgl.uniform=(e,t)=>{let r=Array.isArray(t)?t.length-1:0,a=[["uniform1f",0,"float"],["uniform2fv",[0,0],"vec2"]],i={};return i.name=e,i.type=a[r][0],i.value=t||a[r][1],i.inner_type=a[r][2],i.location="",i.dirty=!1,i},webgl.uniforms=[["u_resolution",[0,0]],["u_time",.001*performance.now()],["u_mouse",[0,0]]],webgl.uniforms.forEach(((e,t)=>webgl.uniforms[t]=webgl.uniform(e[0],e[1]))),webgl.create_shader=(e,t,r)=>{let a=e.createShader(t);return webgl.shaderSource(a,r),webgl.compileShader(a),a},webgl.resize=()=>{canvas.width=w.innerWidth*device_ratio,canvas.height=w.innerHeight*device_ratio,canvas.style.width="100%",canvas.style.height="100%";let e=webgl.uniforms[0];e.value=[canvas.width,canvas.height],e.dirty=!0},webgl.render=()=>{webgl.viewport(0,0,canvas.width,canvas.height);let e=webgl.uniforms[1];e.value=.001*performance.now(),e.dirty=!0;let t=webgl.uniforms.filter((e=>1==e.dirty));for(let e in t)webgl[t[e].type](t[e].location,t[e].value),t[e].dirty=!1;webgl.drawArrays(webgl.TRIANGLE_STRIP,0,4),webgl.readPixels(0,0,1,1,webgl.RGBA,webgl.UNSIGNED_BYTE,pixel)},webgl.is_valid=()=>null!=webgl.program,webgl.start_update=()=>{webgl.render(),webgl.frame=requestAnimationFrame(webgl.start_update)},webgl.stop_update=()=>{webgl.frame&&cancelAnimationFrame(webgl.frame)},webgl.change_aa=e=>{frag_piece=frag_piece.replace("#define AA 2",`#define AA ${e}`)};let pointer,load_shader=(e,t)=>{null==t&&(t=vert_shader);let r=webgl;r.stop_update(),r.deleteProgram(r.program),r.program=r.createProgram();const a=webgl.create_shader(r,r.VERTEX_SHADER,t),i=webgl.create_shader(r,r.FRAGMENT_SHADER,e);r.attachShader(r.program,a),r.attachShader(r.program,i),r.linkProgram(r.program);for(let e in webgl.uniforms){let t=webgl.uniforms[e];t.location=r.getUniformLocation(r.program,t.name),t.dirty=!0}let o=Float32Array.of(-1,1,-1,-1,1,1,1,-1),n=r.createBuffer(),c=r.getAttribLocation(r.program,"p");r.bindBuffer(r.ARRAY_BUFFER,n),r.bufferData(r.ARRAY_BUFFER,o,r.STATIC_DRAW),r.enableVertexAttribArray(c),r.vertexAttribPointer(c,2,r.FLOAT,!1,0,0),r.useProgram(r.program),r.resize()},start_shader=(e,t)=>{is_mobile&&webgl.change_aa(1),load_shader(e,t),webgl.start_update()};pointer=w.PointerEvent?{start:["pointerdown"],move:["pointermove"],end:["pointerup"]}:{start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]};let drag={update_uniform:e=>{let t=webgl.uniforms[0].value,r=webgl.uniforms[2];r.value=[e.clientX,t[1]-e.clientY],r.dirty=!0},update:e=>{drag.update_uniform(e)},start:e=>{webgl.is_valid&&(drag.update_uniform(e),pointer.move.forEach((e=>{document.addEventListener(e,drag.update)})))},stop:e=>{webgl.is_valid&&(drag.update_uniform(e),pointer.move.forEach((e=>{document.removeEventListener(e,drag.update)})))}},resize=()=>{if(!webgl.is_valid)return;let e=webgl.uniforms[0].value;webgl.resize();let t=webgl.uniforms[0].value,r=[t[0]/e[0],t[1]/e[1]],a=webgl.uniforms[2];a.value=[a.value[0]*r[0],a.value[1]*r[1]],a.dirty=!0};const SIGNATURE_SVG="data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxMzguNjcgMTQ2Ljg5Jz48cGF0aCBmaWxsPSd3aGl0ZScgZD0nbTEyMS45NCAwIDIuNzMgNC4zLTQ2Ljg1IDkuNThMNi4xIDI1LjI4bC0xLjQ5LTUuMzVMMTIxLjk0IDB6Jy8+PHBhdGggZmlsbD0nd2hpdGUnIGQ9J002LjI0IDguMzMgMi45NSA1LjU1IDAgOC40OGwxNS40MyAxMDMuNzctMi44OSA0LjQ5IDIuMTEgMi4xMiA2LjM0LTUuOC0uNDYtNi41M0w2LjI0IDguMzN6TTEyOC4zIDkuMzdsMi43Ny0xLjk3IDIuODQgMS4xNC0xLjU0IDE2LjU3LTEuNzggMzguMS45NSAyMy4yOCAzLjQ4IDI1Ljk3IDMuNjUgMTkuMTEtMS45NSAzLjg3LTMuOTYtMS45My00LjUxLTI1Ljc5LTMuMDItMjQuNzEtLjg1LTI0LjQyLjk2LTI1Ljc3IDIuOTYtMjMuNDV6TTkuMjIgMTM4LjcxbC0zLjc1IDEuNDUuNDMgMy43IDkuNTMgMy4wMyAzOC41Ni03LjkyIDM1LjIxLTIuOTYgNDAuNjIgMy4xMiAyLjM5LTIuNTYtMi40NC0zLjQtMjMuNTktMi40LTI1LjA3LS4yOC0yNC44NiAyLjMzLTI2LjU0IDQuMzgtMjAuNDkgMS41MXpNNTUuNTMgODAuNTdsMi4zNSAxLjAzIDEuOTktMi42NS0xLjA5LTkuNTFMNzYuNzIgNjZsLTMuMzcgMTkuNTEtMTQuMDkgMS42My0xLjggMi4xIDMuMTkgMi40MSAxMi42NC0uNjYuNzIgMi4yMyAxLjc1LjQyIDIuNjUtMi4yMyAzLjg1LS45Ni0yLjU5LTMuODYtMi43Ny0uNTQgNS40OC0yMC44MyAxLjc1LTMuMzEtMi4zNS0xLjE0LTkuNjMgMS4xNEw1NC4zMyA2NmwtLjk3IDMuMTQgMi4xNyAxMS40M3onLz48L3N2Zz4=",appendSignature=()=>{const e=document.createElement("img");e.src=SIGNATURE_SVG.trim(),e.style.cssText="width:40px;z-index:50;position:fixed;bottom:20px;right:20px;",body.appendChild(e)};if(webgl)start_shader(frag_piece),resize(),pointer.start.forEach((e=>{document.addEventListener(e,drag.start)})),pointer.end.forEach((e=>{document.addEventListener(e,drag.stop)})),window.addEventListener("resize",resize),appendSignature();else{const e=document.createElement("div");e.style.cssText="align-items:center;background:#969696;color:#fff;display:flex;font-family:monospace;font-size:20px;height:100vh;justify-content:center;left:0;position:fixed;top:0;width:100vw;",e.innerHTML="NOT SUPPORTED",document.body.append(e)}'
    );

    modifier onlyOwner() {
        if (owner != msg.sender) {
            revert NotOwner();
        }

        _;
    }

    modifier onlyRoyaltyRecipient() {
        if (royaltyRecipient != msg.sender) {
            revert NotRoyaltyRecipient();
        }

        _;
    }

    struct Offer {
        bool active;
        uint256 value;
        address toAddress;
    }

    struct Bid {
        bool active;
        uint256 value;
        address fromAddress;
    }

    address public owner;

    Offer public currentOffer;

    Bid public currentBid;

    address public royaltyRecipient;

    uint256 public royaltyPercentage;

    mapping (address => uint256) public pendingWithdrawals;

    constructor(uint256 _royaltyPercentage) {
        if (_royaltyPercentage >= 100) {
            revert RoyaltyTooHigh();
        }

        owner = msg.sender;
        royaltyRecipient = msg.sender;
        royaltyPercentage = _royaltyPercentage;

        emit ArtpieceCreated(msg.sender);
    }

    function name() public view virtual returns (string memory) {
        return 'DigitalSoul';
    }

    function symbol() public view virtual returns (string memory) {
        return 'DS';
    }

    function artpiece() public view virtual returns (string memory) {
        return string.concat(
            '<!DOCTYPE html>'
            '<html>'
                '<head>'
                    '<title>', 'DigitalSoul', '</title>'

                    '<meta name="viewport" content="width=device-width, initial-scale=1" />'

                    '<style>body{background:#969696;margin:0;padding:0;overflow:hidden;}</style>'
                '</head>'

                '<body>'
                    '<script type="text/javascript">',
                        CORE,
                    '</script>'
                '</body>'
            '</html>'
        );
    }

    function withdraw() public {
        uint256 amount = pendingWithdrawals[msg.sender];

        pendingWithdrawals[msg.sender] = 0;

        _sendFunds(amount);
    }

    function transferOwnership(address newOwner) public onlyOwner {
        if (newOwner == address(0)) {
            revert NullAddress();
        }

        _transferOwnership(newOwner);

        if (currentBid.fromAddress == newOwner) {
            uint256 amount = currentBid.value;

            currentBid = Bid({ active: false, value: 0, fromAddress: address(0) });

            pendingWithdrawals[newOwner] += amount;
        }

        if (currentOffer.active) {
            currentOffer = Offer({ active: false, value: 0, toAddress: address(0) });
        }
    }

    function listForSale(uint256 salePriceInWei) public onlyOwner {
        currentOffer = Offer({ active: true, value: salePriceInWei, toAddress: address(0) });

        emit ListedForSale(salePriceInWei, msg.sender, address(0));
    }

    function listForSaleToAddress(uint256 salePriceInWei, address toAddress) public onlyOwner {
        currentOffer = Offer({ active: true, value: salePriceInWei, toAddress: toAddress });

        emit ListedForSale(salePriceInWei, msg.sender, toAddress);
    }

    function cancelFromSale() public onlyOwner {
        Offer memory oldOffer = currentOffer;

        currentOffer = Offer({ active: false, value: 0, toAddress: address(0) });

        emit SaleCanceled(oldOffer.value, msg.sender, oldOffer.toAddress);
    }

    function buyNow() public payable {
        if (!currentOffer.active) {
            revert NotForSale();
        }

        if (currentOffer.toAddress != address(0) && currentOffer.toAddress != msg.sender) {
            revert ListedForSaleToSpecificAddress();
        }

        if (msg.value != currentOffer.value) {
            revert InsufficientFunds();
        }

        currentOffer = Offer({ active: false, value: 0, toAddress: address(0) });

        uint256 royaltyAmount = _calcRoyalty(msg.value);

        pendingWithdrawals[owner] += msg.value - royaltyAmount;
        pendingWithdrawals[royaltyRecipient] += royaltyAmount;

        emit SaleCompleted(msg.value, owner, msg.sender);

        _transferOwnership(msg.sender);
    }

    function placeBid() public payable {
        if (msg.value <= currentBid.value) {
            revert InsufficientFunds();
        }

        if (currentBid.value > 0) {
            pendingWithdrawals[currentBid.fromAddress] += currentBid.value;
        }

        currentBid = Bid({ active: true, value: msg.value, fromAddress: msg.sender });

        emit BidPlaced(msg.value, msg.sender);
    }

    function acceptBid() public onlyOwner {
        if (!currentBid.active) {
            revert NoBid();
        }

        uint256 amount = currentBid.value;
        address bidder = currentBid.fromAddress;

        currentOffer = Offer({ active: false, value: 0, toAddress: address(0) });
        currentBid = Bid({ active: false, value: 0, fromAddress: address(0) });

        uint256 royaltyAmount = _calcRoyalty(amount);

        pendingWithdrawals[owner] += amount - royaltyAmount;
        pendingWithdrawals[royaltyRecipient] += royaltyAmount;

        emit BidAccepted(amount, owner, bidder);

        _transferOwnership(bidder);
    }

    function withdrawBid() public {
        if (msg.sender != currentBid.fromAddress) {
            revert NotYourBid();
        }

        uint256 amount = currentBid.value;

        currentBid = Bid({ active: false, value: 0, fromAddress: address(0) });

        _sendFunds(amount);

        emit BidWithdrawn(amount, msg.sender);
    }

    function setRoyaltyRecipient(address newRoyaltyRecipient) public onlyRoyaltyRecipient {
        if (newRoyaltyRecipient == address(0)) {
            revert NullAddress();
        }

        royaltyRecipient = newRoyaltyRecipient;
    }

    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = owner;

        owner = newOwner;

        emit ArtpieceTransferred(oldOwner, newOwner);
    }

    function _sendFunds(uint256 amount) internal virtual {
        (bool success, ) = msg.sender.call{value: amount}('');

        if (!success) {
            revert FundsTransfer();
        }
    }

    function _calcRoyalty(uint256 amount) internal virtual returns (uint256) {
        return (amount * royaltyPercentage) / 100;
    }
}